Normalizing path strings and separators in cross-platform unit test scripts

Chris Angelico rosuav at gmail.com
Mon Jan 7 13:56:37 EST 2019


On Tue, Jan 8, 2019 at 5:52 AM Malcolm Greene <python at bdurham.com> wrote:
>
> Any recommendations on normalizing path strings in cross platform
> (Windows, Linux, macOS) for unit tests?
> Our goal is to normalize path strings to use forward slash separators so
> that we can consistently reference path strings in our unit tests in a
> cross platform way.
> Example: Under Windows we have two paths that are logically the same but fail to match for test purposes.
> assert str(full_path(f'{test_folder_path}/readonly.txt')) == 'C:/udp-app-
> master/dev/tmp/readonly.txt'E       AssertionError: assert 'C:\\udp-app-...\readonly.txt' == 'C:/udp-app-
> ma.../readonly.txt'
> Is there a best practice way to convert Windows style paths (with
> backslash path separators) to Linux style paths with forward slash path
> separators? I've looked at the os and pathlib libraries without seeing
> anything that describes our need.
> Any downsides to this approach?

If you are confident you'll never have an actual backslash in a path
name (which would be a requirement if they're cross-platform anyway),
you could just p.replace("\\", "/") to convert them. I don't think
that will break anything on any Windows-based or Unix-based OS (could
be wrong of course).

ChrisA



More information about the Python-list mailing list