Python re.escape() Examples
The following are 30
code examples of re.escape().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
re
, or try the search function
.

Example #1
Source File: test_exception_trace.py From clikit with MIT License | 7 votes |
def test_render_debug_better_error_message_recursion_error_with_multiple_duplicated_frames(): io = BufferedIO() io.set_verbosity(VERBOSE) with pytest.raises(RecursionError) as e: first() trace = ExceptionTrace(e.value) trace.render(io) expected = r"... Previous 2 frames repeated \d+ times".format( filename=re.escape(trace._get_relative_file_path(__file__)), ) assert re.search(expected, io.fetch_output()) is not None
Example #2
Source File: test_smbclient_os.py From smbprotocol with MIT License | 6 votes |
def test_write_exclusive_text_file(smb_share): file_path = "%s\\%s" % (smb_share, "file.txt") file_contents = u"File Contents\nNewline" with smbclient.open_file(file_path, mode='x') as fd: assert isinstance(fd, io.TextIOWrapper) assert fd.closed is False with pytest.raises(IOError): fd.read() assert fd.tell() == 0 fd.write(file_contents) assert int(fd.tell()) == (len(file_contents) - 1 + len(os.linesep)) assert fd.closed is True with smbclient.open_file(file_path, mode='r') as fd: assert fd.read() == file_contents with pytest.raises(OSError, match=re.escape("[NtStatus 0xc0000035] File exists: ")): smbclient.open_file(file_path, mode='x') assert fd.closed is True
Example #3
Source File: test_smbclient_shutil.py From smbprotocol with MIT License | 6 votes |
def test_copymode_local_to_local_symlink_dont_follow(tmpdir): test_dir = tmpdir.mkdir('test') src_filename = "%s\\source.txt" % test_dir dst_filename = "%s\\target.txt" % test_dir with open(src_filename, mode='w') as fd: fd.write(u"content") os.chmod(src_filename, stat.S_IREAD) with open(dst_filename, mode='w') as fd: fd.write(u"content") src_link = "%s\\source-link.txt" % test_dir dst_link = "%s\\target-link.txt" % test_dir os.symlink(src_filename, src_link) os.symlink(dst_filename, dst_link) expected = "chmod: follow_symlinks unavailable on this platform" with pytest.raises(NotImplementedError, match=re.escape(expected)): copymode(src_link, dst_link, follow_symlinks=False)
Example #4
Source File: test_smbclient_shutil.py From smbprotocol with MIT License | 6 votes |
def test_rmtree_non_existing(smb_share): dir_name = "%s\\dir2" % smb_share expected = "[NtStatus 0xc0000034] No such file or directory: " with pytest.raises(OSError, match=re.escape(expected)): rmtree(dir_name) rmtree(dir_name, ignore_errors=True) callback_args = [] def callback(*args): callback_args.append(args) rmtree(dir_name, onerror=callback) assert len(callback_args) == 2 assert callback_args[0][0].__name__ == 'scandir' assert callback_args[0][1] == dir_name assert isinstance(callback_args[0][2][1], SMBOSError) assert callback_args[1][0].__name__ == 'rmdir' assert callback_args[1][1] == dir_name assert isinstance(callback_args[1][2][1], SMBOSError)
Example #5
Source File: test_smbclient_shutil.py From smbprotocol with MIT License | 6 votes |
def test_rmtree_as_file(smb_share): filename = "%s\\file.txt" % smb_share with open_file(filename, mode='w') as fd: fd.write(u"content") expected = "[NtStatus 0xc0000103] Not a directory: " with pytest.raises(OSError, match=re.escape(expected)): rmtree(filename) rmtree(filename, ignore_errors=True) callback_args = [] def callback(*args): callback_args.append(args) rmtree(filename, onerror=callback) assert len(callback_args) == 2 assert callback_args[0][0].__name__ == 'scandir' assert callback_args[0][1] == filename assert isinstance(callback_args[0][2][1], SMBOSError) assert callback_args[1][0].__name__ == 'rmdir' assert callback_args[1][1] == filename assert isinstance(callback_args[1][2][1], SMBOSError)
Example #6
Source File: test_smbclient_shutil.py From smbprotocol with MIT License | 6 votes |
def test_rmtree_symlink_as_dir(smb_share): src_dirname = "%s\\dir" % smb_share dst_dirname = "%s\\target" % smb_share mkdir(src_dirname) symlink("dir", dst_dirname) expected = "Cannot call rmtree on a symbolic link" with pytest.raises(OSError, match=re.escape(expected)): rmtree(dst_dirname) assert exists(src_dirname) assert exists(dst_dirname) rmtree(dst_dirname, ignore_errors=True) callback_args = [] def callback(*args): callback_args.append(args) rmtree(dst_dirname, onerror=callback) assert len(callback_args) == 1 assert callback_args[0][0].__name__ == 'islink' assert callback_args[0][1] == dst_dirname assert isinstance(callback_args[0][2][1], OSError)
Example #7
Source File: test_exceptions.py From smbprotocol with MIT License | 6 votes |
def test_resolve_path_local_fail(self): b_sub_name = to_bytes(u'\\??\\C:\\foldér', encoding='utf-16-le') b_print_name = to_bytes(u'C:\\foldér', encoding='utf-16-le') resp = SMB2SymbolicLinkErrorResponse() resp['unparsed_path_length'] = 0 resp['substitute_name_offset'] = 0 resp['substitute_name_length'] = len(b_sub_name) resp['print_name_offset'] = len(b_sub_name) resp['print_name_length'] = len(b_print_name) resp['flags'] = SymbolicLinkErrorFlags.SYMLINK_FLAG_ABSOLUTE resp['path_buffer'] = b_sub_name + b_print_name link_path = u'\\\\sérver\\sharé\\foldér' expected = u"Encountered symlink at '%s' that points to 'C:\\foldér' which cannot be redirected: Cannot " \ u"resolve link targets that point to a local path" % link_path with pytest.raises(SMBLinkRedirectionError, match=re.escape(to_native(expected))): resp.resolve_path(link_path)
Example #8
Source File: test_exceptions.py From smbprotocol with MIT License | 6 votes |
def test_resolve_path_different_share(self): b_sub_name = to_bytes(u'\\??\\UNC\\other-sérver\\sharé\\foldér', encoding='utf-16-le') b_print_name = to_bytes(u'\\\\other-sérver\\sharé\\foldér', encoding='utf-16-le') resp = SMB2SymbolicLinkErrorResponse() resp['unparsed_path_length'] = 0 resp['substitute_name_offset'] = 0 resp['substitute_name_length'] = len(b_sub_name) resp['print_name_offset'] = len(b_sub_name) resp['print_name_length'] = len(b_print_name) resp['flags'] = SymbolicLinkErrorFlags.SYMLINK_FLAG_ABSOLUTE resp['path_buffer'] = b_sub_name + b_print_name link_path = u'\\\\sérver\\sharé\\foldér' expected = u"Encountered symlink at '%s' that points to '\\\\other-sérver\\sharé\\foldér' which cannot be " \ u"redirected: Cannot resolve link targets that point to a different host/share" % link_path with pytest.raises(SMBLinkRedirectionError, match=re.escape(to_native(expected))): resp.resolve_path(link_path)
Example #9
Source File: test_exceptions.py From smbprotocol with MIT License | 6 votes |
def test_resolve_path_different_host(self): b_sub_name = to_bytes(u'\\??\\UNC\\sérver\\sharé2\\foldér', encoding='utf-16-le') b_print_name = to_bytes(u'\\\\sérver\\sharé2\\foldér', encoding='utf-16-le') resp = SMB2SymbolicLinkErrorResponse() resp['unparsed_path_length'] = 0 resp['substitute_name_offset'] = 0 resp['substitute_name_length'] = len(b_sub_name) resp['print_name_offset'] = len(b_sub_name) resp['print_name_length'] = len(b_print_name) resp['flags'] = SymbolicLinkErrorFlags.SYMLINK_FLAG_ABSOLUTE resp['path_buffer'] = b_sub_name + b_print_name link_path = u'\\\\sérver\\sharé\\foldér' expected = u"Encountered symlink at '%s' that points to '\\\\sérver\\sharé2\\foldér' which cannot be " \ u"redirected: Cannot resolve link targets that point to a different host/share" % link_path with pytest.raises(SMBLinkRedirectionError, match=re.escape(to_native(expected))): resp.resolve_path(link_path)
Example #10
Source File: urlextract.py From video2commons with GNU General Public License v3.0 | 6 votes |
def escape_wikitext(wikitext): """Escape wikitext for use in file description.""" rep = OrderedDict([ ('{|', '{{(}}|'), ('|}', '|{{)}}'), ('||', '||'), ('|', '|'), ('[[', '{{!((}}'), (']]', '{{))!}}'), ('{{', '{{((}}'), ('}}', '{{))}}'), ('{', '{{(}}'), ('}', '{{)}}'), ]) rep = dict((re.escape(k), v) for k, v in rep.iteritems()) pattern = re.compile("|".join(rep.keys())) return pattern.sub(lambda m: rep[re.escape(m.group(0))], wikitext) # Source: mediawiki.Title.js@9df363d
Example #11
Source File: uninstall_distro.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def update_grub_cfg_file(uninstall_distro_dir_name): """ Main function to remove uninstall distro name from the grub.cfg file. :return: """ grub_cfg_file = os.path.join(config.usb_mount, "multibootusb", "grub", "grub.cfg") if not os.path.exists(grub_cfg_file): gen.log("grub.cfg file not found for updating changes.") else: gen.log("Updating grub.cfg file...") string = open(grub_cfg_file).read() string = re.sub(r'#start ' + re.escape(uninstall_distro_dir_name) + '.*?' + '#end ' + re.escape(uninstall_distro_dir_name) + r'\s*', '', string, flags=re.DOTALL) config_file = open(grub_cfg_file, "w") config_file.write(string) config_file.close()
Example #12
Source File: uninstall_distro.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def update_sys_cfg_file(uninstall_distro_dir_name): """ Main function to remove uninstall distro specific operations. :return: """ sys_cfg_file = os.path.join(config.usb_mount, "multibootusb", "syslinux.cfg") if not os.path.exists(sys_cfg_file): gen.log("syslinux.cfg file not found for updating changes.") else: gen.log("Updating syslinux.cfg file...") string = open(sys_cfg_file).read() string = re.sub(r'#start ' + re.escape(uninstall_distro_dir_name) + '.*?' + '#end ' + re.escape(uninstall_distro_dir_name) + r'\s*', '', string, flags=re.DOTALL) config_file = open(sys_cfg_file, "w") config_file.write(string) config_file.close()
Example #13
Source File: test_smbclient_os.py From smbprotocol with MIT License | 6 votes |
def test_open_file_with_write_share_access(smb_share): file_path = "%s\\%s" % (smb_share, "file.txt") with smbclient.open_file(file_path, mode='w') as fd: expected = "[NtStatus 0xc0000043] The process cannot access the file because it is being used by " \ "another process: " with pytest.raises(OSError, match=re.escape(expected)): smbclient.open_file(file_path, mode='a') with smbclient.open_file(file_path, mode='w', share_access='w') as fd: fd.write(u"contents") fd.flush() with pytest.raises(OSError): smbclient.open_file(file_path, mode='r') with smbclient.open_file(file_path, mode='a', share_access='w') as fd_child: fd_child.write(u"\nnewline") with smbclient.open_file(file_path, mode='r') as fd: assert fd.read() == u"contents\nnewline"
Example #14
Source File: test_smbclient_os.py From smbprotocol with MIT License | 6 votes |
def test_open_file_with_read_share_access(smb_share): file_path = "%s\\%s" % (smb_share, "file.txt") with smbclient.open_file(file_path, mode='w') as fd: fd.write(u"contents") with smbclient.open_file(file_path): expected = "[NtStatus 0xc0000043] The process cannot access the file because it is being used by " \ "another process" with pytest.raises(OSError, match=re.escape(expected)): smbclient.open_file(file_path) with smbclient.open_file(file_path, share_access='r') as fd: assert fd.read() == u"contents" with smbclient.open_file(file_path, share_access='r') as fd_child: assert fd_child.read() == u"contents" with pytest.raises(OSError): smbclient.open_file(file_path, mode='a')
Example #15
Source File: test_smbclient_os.py From smbprotocol with MIT License | 6 votes |
def test_write_exclusive_byte_file(smb_share): file_path = "%s\\%s" % (smb_share, "file.txt") file_contents = b"File Contents\nNewline" with smbclient.open_file(file_path, mode='xb') as fd: assert isinstance(fd, io.BufferedWriter) assert fd.closed is False with pytest.raises(IOError): fd.read() assert fd.tell() == 0 fd.write(file_contents) assert fd.tell() == len(file_contents) assert fd.closed is True with smbclient.open_file(file_path, mode='rb') as fd: assert fd.read() == file_contents with pytest.raises(OSError, match=re.escape("[NtStatus 0xc0000035] File exists: ")): smbclient.open_file(file_path, mode='xb') assert fd.closed is True
Example #16
Source File: test.py From PHATE with GNU General Public License v2.0 | 5 votes |
def assert_raises_message(expected_warning, expected_message, *args, **kwargs): expected_regex = re.escape(expected_message) return assert_raises_regex(expected_warning, expected_regex, *args, **kwargs)
Example #17
Source File: setupbase.py From jupyterlab-sidecar with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _translate_glob_part(pat): """Translate a glob PATTERN PART to a regular expression.""" # Code modified from Python 3 standard lib fnmatch: if pat == '**': return '.*' i, n = 0, len(pat) res = [] while i < n: c = pat[i] i = i + 1 if c == '*': # Match anything but path separators: res.append('[^%s]*' % SEPARATORS) elif c == '?': res.append('[^%s]?' % SEPARATORS) elif c == '[': j = i if j < n and pat[j] == '!': j = j + 1 if j < n and pat[j] == ']': j = j + 1 while j < n and pat[j] != ']': j = j + 1 if j >= n: res.append('\\[') else: stuff = pat[i:j].replace('\\', '\\\\') i = j + 1 if stuff[0] == '!': stuff = '^' + stuff[1:] elif stuff[0] == '^': stuff = '\\' + stuff res.append('[%s]' % stuff) else: res.append(re.escape(c)) return ''.join(res)
Example #18
Source File: test.py From PHATE with GNU General Public License v2.0 | 5 votes |
def assert_warns_message(expected_warning, expected_message, *args, **kwargs): expected_regex = re.escape(expected_message) return assert_warns_regex(expected_warning, expected_regex, *args, **kwargs)
Example #19
Source File: setupbase.py From jupyterlab-sidecar with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _translate_glob(pat): """Translate a glob PATTERN to a regular expression.""" translated_parts = [] for part in _iexplode_path(pat): translated_parts.append(_translate_glob_part(part)) os_sep_class = '[%s]' % re.escape(SEPARATORS) res = _join_translated(translated_parts, os_sep_class) return '{res}\\Z(?ms)'.format(res=res)
Example #20
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_set_utime_bad_tuple(): expected = "The time tuple should be a 2-tuple of the form (atime, mtime)" with pytest.raises(ValueError, match=re.escape(expected)): smbclient.utime("", times=(0, 0, 0))
Example #21
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_rmdir_non_empty_dir(smb_share): dir_name = "%s\\directory" % smb_share smbclient.mkdir(dir_name) with smbclient.open_file("%s\\file.txt" % dir_name, mode='w') as fd: fd.write(u"content") expected = "[NtStatus 0xc0000101] Directory not empty: " with pytest.raises(OSError, match=re.escape(expected)): smbclient.rmdir(dir_name)
Example #22
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_rmdir(smb_share): dir_name = "%s\\directory" % smb_share smbclient.mkdir(dir_name) assert smbclient.listdir(smb_share) == ['directory'] smbclient.rmdir(dir_name) assert smbclient.listdir(smb_share) == [] expected = "[NtStatus 0xc0000034] No such file or directory: " with pytest.raises(OSError, match=re.escape(expected)): smbclient.rmdir(dir_name)
Example #23
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_open_file_in_missing_dir(smb_share): file_path = "%s\\dir\\%s" % (smb_share, "file.txt") with pytest.raises(OSError, match=re.escape("[NtStatus 0xc000003a] No such file or directory: ")): smbclient.open_file(file_path)
Example #24
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_rename_fail_dst_not_absolute(smb_share): expected = "dst must be an absolute path to where the file or directory should be renamed." with pytest.raises(ValueError, match=re.escape(expected)): smbclient.rename(smb_share, "not_absolute")
Example #25
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_remove_file_that_is_opened_without_delete_access(smb_share): filename = "%s\\delete-me.txt" % smb_share with smbclient.open_file(filename, mode='wb') as fd: fd.write(b"Content") assert smbclient.listdir(smb_share) == ['delete-me.txt'] # Because our other handle does not have the d share_access set, this should fail expected = "The process cannot access the file because it is being used by another process" with pytest.raises(SMBOSError, match=re.escape(expected)): smbclient.remove(filename)
Example #26
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_readlink_not_symlink(monkeypatch): def a(*args, **kwargs): buffer = ReparseDataBuffer() buffer['reparse_tag'] = 1 buffer['data_buffer'] = b"" return buffer monkeypatch.setattr(smbclient._os, "_get_reparse_point", a) expected = "Cannot read link of reparse point with tag (1) IO_REPARSE_TAG_RESERVED_ONE at 'path'" with pytest.raises(ValueError, match=re.escape(expected)): smbclient.readlink("path")
Example #27
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_open_file_invalid_share_access(smb_share): with pytest.raises(ValueError, match=re.escape("Invalid share_access char z, can only be d, r, w")): smbclient.open_file(smb_share, share_access='z')
Example #28
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_open_file_invalid_mode_char(smb_share): with pytest.raises(ValueError, match=re.escape("Invalid mode char z, can only be +, a, b, r, t, w, x")): smbclient.open_file(smb_share, mode='z')
Example #29
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_open_file_unbuffered_text_file(smb_share): expected = "can't have unbuffered text I/O" with pytest.raises(ValueError, match=re.escape(expected)): smbclient.open_file("%s\\file.txt" % smb_share, mode='w', buffering=0)
Example #30
Source File: test_smbclient_os.py From smbprotocol with MIT License | 5 votes |
def test_readlink_normal_file(smb_share): filename = "%s\\file.txt" % smb_share with smbclient.open_file(filename, mode='w') as fd: fd.write(u"content") expected = "[NtStatus 0xc0000275] The file or directory is not a reparse point" with pytest.raises(OSError, match=re.escape(expected)): smbclient.readlink(filename)