Skip to content

Commit 309f052

Browse files
authored
Merge pull request #249 from statisticsnorway/conf-test
Bedre tester etter refaktorisering
2 parents f0bc1ed + 4b79167 commit 309f052

File tree

4 files changed

+215
-91
lines changed

4 files changed

+215
-91
lines changed

src/statbank/auth.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ def __call__( # noqa: D102
4646
request.headers["Authorization"] = f"{self.auth_scheme} {self.token}"
4747
return request
4848

49+
def __eq__(self: Self, other: object) -> bool: # noqa: D105
50+
return (
51+
isinstance(other, TokenAuth)
52+
and self.token == other.token
53+
and self.auth_scheme == other.auth_scheme
54+
)
55+
56+
def __hash__(self: Self) -> int: # noqa: D105
57+
return hash((self.auth_scheme, self.token))
58+
4959

5060
class StatbankConfig:
5161
"""Holds config for Transfer-API" and "Uttaksbeskrivelse-API."""
@@ -78,6 +88,12 @@ def from_environ(cls: type[Self], use_db: UseDb | None) -> Self:
7888
env_key_endpoint_base = "STATBANK_TEST_BASE_URL"
7989
env_key_encrypt_url = "STATBANK_TEST_ENCRYPT_URL"
8090

91+
elif use_db == UseDb.PROD and environment == DaplaEnvironment.TEST:
92+
error_message = (
93+
"Statbankens produksjonsmiljø ikke tilgjengelig fra Daplas testmiljø"
94+
)
95+
raise RuntimeError(error_message)
96+
8197
else:
8298
env_key_endpoint_base = "STATBANK_BASE_URL"
8399
env_key_encrypt_url = "STATBANK_ENCRYPT_URL"

tests/conftest.py

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,21 +51,58 @@ def fake_request(*_: Any, **__: Any):
5151

5252

5353
@pytest.fixture(autouse=True)
54-
def modify_env():
55-
os.environ["JUPYTERHUB_USER"] = "ssb@ssb.no"
56-
os.environ["DAPLA_USER"] = "usr@ssb.no"
57-
os.environ["DAPLA_ENVIRONMENT"] = "DEV"
54+
def modify_env(monkeypatch: MonkeyPatch):
55+
monkeypatch.setenv("JUPYTERHUB_USER", "ssb@ssb.no")
56+
monkeypatch.setenv("DAPLA_USER", "usr@ssb.no")
57+
monkeypatch.setenv("DAPLA_ENVIRONMENT", "DEV")
5858

59-
os.environ["STATBANK_BASE_URL"] = os.environ.get(
59+
monkeypatch.setenv(
6060
"STATBANK_BASE_URL",
61-
"https://test_fake_url/",
61+
os.environ.get(
62+
"STATBANK_BASE_URL",
63+
"https://test_fake_url/",
64+
),
6265
)
63-
os.environ["STATBANK_ENCRYPT_URL"] = os.environ.get(
66+
monkeypatch.setenv(
6467
"STATBANK_ENCRYPT_URL",
65-
"https://fake_url2/",
68+
os.environ.get(
69+
"STATBANK_ENCRYPT_URL",
70+
"https://fake_url2/",
71+
),
6672
)
6773

6874

75+
@pytest.fixture
76+
def mock_environ_dapla_lab_prod(monkeypatch: MonkeyPatch) -> None:
77+
monkeypatch.setenv("DAPLA_ENVIRONMENT", "PROD")
78+
monkeypatch.setenv("DAPLA_SERVICE", "VS_CODE")
79+
monkeypatch.setenv("DAPLA_REGION", "DAPLA_LAB")
80+
monkeypatch.setenv("STATBANK_ENCRYPT_URL", "https://fakeurl.com/encrypt")
81+
monkeypatch.setenv("STATBANK_TEST_ENCRYPT_URL", "https://test.fakeurl.com/encrypt")
82+
monkeypatch.setenv("STATBANK_BASE_URL", "https://fakeurl.com")
83+
monkeypatch.setenv("STATBANK_TEST_BASE_URL", "https://test.fakeurl.com")
84+
85+
86+
@pytest.fixture
87+
def mock_environ_dapla_lab_test(monkeypatch: MonkeyPatch):
88+
monkeypatch.setenv("DAPLA_ENVIRONMENT", "TEST")
89+
monkeypatch.setenv("DAPLA_SERVICE", "VS_CODE")
90+
monkeypatch.setenv("DAPLA_REGION", "DAPLA_LAB")
91+
monkeypatch.setenv("STATBANK_ENCRYPT_URL", "https://test.fakeurl.com/encrypt")
92+
monkeypatch.setenv("STATBANK_BASE_URL", "https://test.fakeurl.com")
93+
94+
95+
@pytest.fixture
96+
def mock_environ_on_prem_prod(monkeypatch: MonkeyPatch):
97+
monkeypatch.setenv("DAPLA_ENVIRONMENT", "PROD")
98+
monkeypatch.setenv("DAPLA_SERVICE", "JUPYTERHUB")
99+
monkeypatch.setenv("DAPLA_REGION", "ON_PREM")
100+
monkeypatch.setenv("STATBANK_ENCRYPT_URL", "https://fakeurl.com/encrypt")
101+
monkeypatch.setenv("STATBANK_TEST_ENCRYPT_URL", "https://test.fakeurl.com/encrypt")
102+
monkeypatch.setenv("STATBANK_BASE_URL", "https://fakeurl.com")
103+
monkeypatch.setenv("STATBANK_TEST_BASE_URL", "https://test.fakeurl.com")
104+
105+
69106
@pytest.fixture
70107
def config_fixture() -> StatbankConfig:
71108
return StatbankConfig(

tests/test_auth.py

Lines changed: 68 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from pathlib import Path
2-
from typing import Any
32
from typing import cast
43
from unittest import mock
54

@@ -10,46 +9,13 @@
109

1110
from statbank.auth import StatbankAuth
1211
from statbank.auth import StatbankConfig
12+
from statbank.auth import TokenAuth
1313
from statbank.auth import UseDb
1414
from statbank.globals import DaplaEnvironment
1515
from statbank.globals import DaplaRegion
1616
from statbank.writable_netrc import Netrc
1717

1818

19-
# Mock for os.environ.get
20-
@pytest.fixture
21-
def mock_environ_test():
22-
with mock.patch.dict(
23-
"os.environ",
24-
{
25-
"DAPLA_ENVIRONMENT": "TEST",
26-
"DAPLA_SERVICE": "JUPYTERLAB",
27-
"DAPLA_REGION": "ON_PREM",
28-
"STATBANK_ENCRYPT_URL": "https://fakeurl.com/encrypt",
29-
"STATBANK_BASE_URL": "https://fakeurl.com/",
30-
},
31-
):
32-
yield
33-
34-
35-
@pytest.fixture
36-
def mock_environ_prod_dapla():
37-
with mock.patch.dict(
38-
"os.environ",
39-
{
40-
"DAPLA_ENVIRONMENT": "PROD",
41-
"DAPLA_SERVICE": "JUPYTERLAB",
42-
"DAPLA_REGION": "ON_PREM",
43-
"STATBANK_ENCRYPT_URL": "https://fakeurl.com/encrypt",
44-
"STATBANK_TEST_ENCRYPT_URL": "https://test.fakeurl.com/encrypt",
45-
"STATBANK_BASE_URL": "https://fakeurl.com/",
46-
"STATBANK_TEST_BASE_URL": "https://test.fakeurl.com/",
47-
},
48-
):
49-
yield
50-
51-
52-
# Mock for getpass.getpass
5319
@pytest.fixture
5420
def patch_getpass(monkeypatch: pytest.MonkeyPatch):
5521
def getpass_return(prompt: str) -> str:
@@ -63,56 +29,25 @@ def getpass_return(prompt: str) -> str:
6329

6430

6531
@pytest.fixture
66-
def fake_encrypt_response(monkeypatch: pytest.MonkeyPatch, fake_auth: str) -> None:
67-
def fake_request(*_: Any, **__: Any):
68-
mock_response = mock.Mock(spec_set=Response)
69-
mock_response.json.return_value = {"message": fake_auth}
70-
return mock_response
71-
72-
monkeypatch.setattr("requests.post", fake_request)
73-
74-
75-
@pytest.mark.usefixtures("mock_environ_test")
76-
def test_build_urls(
77-
auth_fixture: requests.auth.AuthBase,
78-
) -> None:
79-
# Instantiate the class
80-
statbank_auth = StatbankAuth(use_db=UseDb.PROD, auth=auth_fixture)
32+
def fake_encrypt_response(monkeypatch: pytest.MonkeyPatch, fake_auth: str) -> mock.Mock:
33+
mock_response = mock.Mock(spec_set=Response)
34+
mock_response.json.return_value = {"message": fake_auth}
8135

82-
# Call the _build_urls method
83-
urls = statbank_auth._build_urls() # noqa: SLF001
36+
mock_post = mock.Mock(return_value=mock_response)
37+
monkeypatch.setattr("requests.post", mock_post)
8438

85-
# Verify the expected URLs
86-
expected_urls = {
87-
"loader": furl("https://fakeurl.com/statbank/sos/v1/DataLoader"),
88-
"uttak": furl("https://fakeurl.com/statbank/sos/v1/uttaksbeskrivelse"),
89-
"gui": furl("https://fakeurl.com/lastelogg/gui"),
90-
"api": furl("https://fakeurl.com/lastelogg/api"),
91-
}
92-
assert urls == expected_urls
39+
return mock_post
9340

9441

95-
@pytest.mark.usefixtures("mock_environ_prod_dapla")
96-
def test_build_urls_testdb_from_prod(
97-
auth_fixture: requests.auth.AuthBase,
98-
) -> None:
99-
# Instantiate the class
100-
statbank_auth = StatbankAuth(use_db=UseDb.TEST, auth=auth_fixture)
101-
102-
# Call the _build_urls method
103-
urls = statbank_auth._build_urls() # noqa: SLF001
104-
105-
# Verify the expected URLs
106-
expected_urls = {
107-
"loader": furl("https://test.fakeurl.com/statbank/sos/v1/DataLoader"),
108-
"uttak": furl("https://test.fakeurl.com/statbank/sos/v1/uttaksbeskrivelse"),
109-
"gui": furl("https://test.fakeurl.com/lastelogg/gui"),
110-
"api": furl("https://test.fakeurl.com/lastelogg/api"),
111-
}
112-
assert urls == expected_urls
42+
@pytest.fixture
43+
def patch_dapla_auth(monkeypatch: pytest.MonkeyPatch) -> None:
44+
monkeypatch.setattr(
45+
"dapla_auth_client.AuthClient.fetch_personal_token",
46+
lambda: "token",
47+
)
11348

11449

115-
@pytest.mark.usefixtures("mock_environ_prod_dapla")
50+
@pytest.mark.usefixtures("mock_environ_on_prem_prod")
11651
def test_check_databases_from_prod(
11752
auth_fixture: requests.auth.AuthBase,
11853
) -> None:
@@ -122,8 +57,12 @@ def test_check_databases_from_prod(
12257
assert statbank_auth.check_database() == "TEST"
12358

12459

125-
@pytest.mark.usefixtures("fake_encrypt_response", "patch_getpass")
126-
def test_auth_without_authfile(empty_netrc_file: Path, fake_auth: str):
60+
@pytest.mark.usefixtures("patch_getpass", "patch_dapla_auth")
61+
def test_auth_without_authfile(
62+
empty_netrc_file: Path,
63+
fake_auth: str,
64+
fake_encrypt_response: mock.Mock,
65+
):
12766
config = StatbankConfig(
12867
environment=DaplaEnvironment.PROD,
12968
region=DaplaRegion.ON_PREM,
@@ -134,14 +73,53 @@ def test_auth_without_authfile(empty_netrc_file: Path, fake_auth: str):
13473
)
13574

13675
statbankauth = StatbankAuth(config=config)
76+
77+
fake_encrypt_response.assert_called_once_with(
78+
config.encrypt_url.url,
79+
json={"message": "qwerty"},
80+
auth=None,
81+
timeout=mock.ANY,
82+
)
83+
84+
auth = statbankauth._auth # noqa: SLF001
85+
86+
assert isinstance(auth, requests.auth.HTTPBasicAuth)
87+
assert auth.username == "kari"
88+
assert auth.password == fake_auth
89+
90+
91+
@pytest.mark.usefixtures("patch_getpass", "patch_dapla_auth")
92+
def test_auth_without_authfile_dapla_lab(
93+
empty_netrc_file: Path,
94+
fake_auth: str,
95+
fake_encrypt_response: mock.Mock,
96+
):
97+
config = StatbankConfig(
98+
environment=DaplaEnvironment.PROD,
99+
region=DaplaRegion.DAPLA_LAB,
100+
endpoint_base=furl("https://fakeurl.com"),
101+
encrypt_url=furl("https://fakeurl.com/encrypt"),
102+
useragent="statbank-test",
103+
netrc_path=empty_netrc_file,
104+
)
105+
106+
statbankauth = StatbankAuth(config=config)
107+
108+
fake_encrypt_response.assert_called_once_with(
109+
config.encrypt_url.url,
110+
json={"message": "qwerty"},
111+
auth=TokenAuth("token"),
112+
timeout=mock.ANY,
113+
)
114+
137115
auth = statbankauth._auth # noqa: SLF001
138116

139117
assert isinstance(auth, requests.auth.HTTPBasicAuth)
140118
assert auth.username == "kari"
141119
assert auth.password == fake_auth
142120

143121

144-
@pytest.mark.usefixtures("fake_encrypt_response", "patch_getpass")
122+
@pytest.mark.usefixtures("fake_encrypt_response", "patch_getpass", "patch_dapla_auth")
145123
def test_auth_persisted(empty_netrc_file: Path, fake_auth: str):
146124
config = StatbankConfig(
147125
environment=DaplaEnvironment.PROD,
@@ -161,7 +139,11 @@ def test_auth_persisted(empty_netrc_file: Path, fake_auth: str):
161139

162140

163141
@pytest.mark.usefixtures("patch_getpass")
164-
def test_read_auth_from_authfile(existing_netrc_file: Path, fake_auth: str):
142+
def test_read_auth_from_authfile(
143+
existing_netrc_file: Path,
144+
fake_auth: str,
145+
fake_encrypt_response: mock.Mock,
146+
):
165147
config = StatbankConfig(
166148
environment=DaplaEnvironment.PROD,
167149
region=DaplaRegion.ON_PREM,
@@ -172,6 +154,9 @@ def test_read_auth_from_authfile(existing_netrc_file: Path, fake_auth: str):
172154
)
173155

174156
statbankauth = StatbankAuth(use_db=UseDb.PROD, config=config)
157+
158+
fake_encrypt_response.assert_not_called()
159+
175160
auth = statbankauth._auth # noqa: SLF001
176161

177162
assert isinstance(auth, requests.auth.HTTPBasicAuth)

0 commit comments

Comments
 (0)