|
| 1 | +import os |
| 2 | +from unittest import mock |
| 3 | + |
| 4 | +from bmi_topography.topography import find_api_key, read_first_of |
| 5 | + |
| 6 | + |
| 7 | +def copy_environ(exclude=None): |
| 8 | + if exclude is None: |
| 9 | + exclude = {} |
| 10 | + elif isinstance(exclude, str): |
| 11 | + exclude = {exclude} |
| 12 | + |
| 13 | + return {key: value for key, value in os.environ.items() if key not in exclude} |
| 14 | + |
| 15 | + |
| 16 | +def test_find_api_key_not_found(): |
| 17 | + """The API key is not given anywhere""" |
| 18 | + env = copy_environ(exclude="OPENTOPOGRAPHY_API_KEY") |
| 19 | + with mock.patch.dict(os.environ, env, clear=True): |
| 20 | + assert find_api_key() == "" |
| 21 | + |
| 22 | + |
| 23 | +@mock.patch.dict(os.environ, {"OPENTOPOGRAPHY_API_KEY": "foo"}) |
| 24 | +def test_find_api_key_env(tmpdir): |
| 25 | + """The API key is an environment variable""" |
| 26 | + with tmpdir.as_cwd(): |
| 27 | + with open(".opentopography.txt", "w") as fp: |
| 28 | + fp.write("bar") |
| 29 | + assert find_api_key() == "foo" |
| 30 | + |
| 31 | + |
| 32 | +@mock.patch.dict(os.environ, {"OPENTOPOGRAPHY_API_KEY": "foo"}) |
| 33 | +def test_find_api_key_from_file(tmpdir): |
| 34 | + """The API key is in a file""" |
| 35 | + env = copy_environ(exclude="OPENTOPOGRAPHY_API_KEY") |
| 36 | + with tmpdir.as_cwd(): |
| 37 | + with open(".opentopography.txt", "w") as fp: |
| 38 | + fp.write("bar") |
| 39 | + |
| 40 | + with mock.patch.dict(os.environ, env, clear=True): |
| 41 | + assert find_api_key() == "bar" |
| 42 | + |
| 43 | + |
| 44 | +def test_read_first_missing(tmpdir): |
| 45 | + with tmpdir.as_cwd(): |
| 46 | + assert read_first_of(["foo.txt"]) == "" |
| 47 | + assert read_first_of([]) == "" |
| 48 | + |
| 49 | + |
| 50 | +def test_read_first_file(tmpdir): |
| 51 | + with tmpdir.as_cwd(): |
| 52 | + with open("foo.txt", "w") as fp: |
| 53 | + fp.write("foo") |
| 54 | + with open("bar.txt", "w") as fp: |
| 55 | + fp.write("bar") |
| 56 | + |
| 57 | + assert read_first_of(["foo.txt", "bar.txt"]) == "foo" |
| 58 | + assert read_first_of(["bar.txt", "foo.txt"]) == "bar" |
0 commit comments