1# Any copyright is dedicated to the Public Domain.
2# https://creativecommons.org/publicdomain/zero/1.0/
3
4from __future__ import absolute_import
5
6import os
7import six
8import sys
9
10import mozunit
11
12from mozfile import which
13
14here = os.path.abspath(os.path.dirname(__file__))
15
16
17def test_which(monkeypatch):
18    cwd = os.path.join(here, "files", "which")
19    monkeypatch.chdir(cwd)
20
21    if sys.platform == "win32":
22        if six.PY3:
23            import winreg
24        else:
25            import _winreg as winreg
26        bindir = os.path.join(cwd, "win")
27        monkeypatch.setenv("PATH", bindir)
28        monkeypatch.setattr(winreg, "QueryValue", (lambda k, sk: None))
29
30        assert which("foo.exe").lower() == os.path.join(bindir, "foo.exe").lower()
31        assert which("foo").lower() == os.path.join(bindir, "foo.exe").lower()
32        assert (
33            which("foo", exts=[".FOO", ".BAR"]).lower()
34            == os.path.join(bindir, "foo").lower()
35        )
36        assert os.environ.get("PATHEXT") != [".FOO", ".BAR"]
37        assert which("foo.txt") is None
38
39        assert which("bar").lower() == os.path.join(bindir, "bar").lower()
40        assert which("baz").lower() == os.path.join(cwd, "baz.exe").lower()
41
42        registered_dir = os.path.join(cwd, "registered")
43        quux = os.path.join(registered_dir, "quux.exe").lower()
44
45        def mock_registry(key, subkey):
46            assert subkey == (
47                r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\quux.exe"
48            )
49            return quux
50
51        monkeypatch.setattr(winreg, "QueryValue", mock_registry)
52        assert which("quux").lower() == quux
53        assert which("quux.exe").lower() == quux
54
55    else:
56        bindir = os.path.join(cwd, "unix")
57        monkeypatch.setenv("PATH", bindir)
58        assert which("foo") == os.path.join(bindir, "foo")
59        assert which("baz") is None
60        assert which("baz", exts=[".EXE"]) is None
61        assert "PATHEXT" not in os.environ
62        assert which("file") is None
63
64
65if __name__ == "__main__":
66    mozunit.main()
67