Skip to content

Commit

Permalink
fix all remaining tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pmayd committed Oct 29, 2023
1 parent 857af8e commit 8fcddc0
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 88 deletions.
16 changes: 10 additions & 6 deletions src/pystatis/db.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging

from pystatis.config import config, get_supported_db, write_config
from pystatis.exception import PystatisConfigError

logger = logging.getLogger(__name__)

Expand All @@ -13,17 +14,20 @@ def set_db(name: str) -> None:
)
config["SETTINGS"]["active_db"] = name.lower()

if not config[name]["username"] or not config[name]["password"]:
logger.critical(
"No credentials for %s found. Please run `setup_credentials()`.",
name,
)


def get_db() -> str:
"""Get the active database."""
active_db = config["SETTINGS"]["active_db"]
if not active_db:
logger.critical("No active database set! Please run `set_db()`.")

if not config[active_db]["username"] or not config[active_db]["password"]:
logger.critical(
"No credentials for %s found. Please run `setup_credentials()`.",
active_db,
if not active_db:
raise PystatisConfigError(
"No active database set! Please run `set_db()`."
)

return active_db
Expand Down
6 changes: 6 additions & 0 deletions src/pystatis/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@ class DestatisStatusError(ValueError):
"""Raised when Destatis status code indicates an error ("Fehler")"""

pass


class PystatisConfigError(Exception):
"""Raised when pystatis configuration is invalid."""

pass
4 changes: 2 additions & 2 deletions src/pystatis/http_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
read_from_cache,
)
from pystatis.config import get_cache_dir
from pystatis.db import get_db_settings
from pystatis import db
from pystatis.exception import DestatisStatusError

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -94,7 +94,7 @@ def get_data_from_endpoint(
Returns:
requests.Response: the response object holding the response from calling the Destatis endpoint.
"""
db_host, db_user, db_pw = get_db_settings()
db_host, db_user, db_pw = db.get_db_settings()
url = f"{db_host}{endpoint}/{method}"

# params is used to calculate hash for caching so don't alter params dict here!
Expand Down
12 changes: 2 additions & 10 deletions src/pystatis/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging
from typing import cast

from pystatis.db import set_db_pw
from pystatis import db, config
from pystatis.http_helper import load_data

logger = logging.getLogger(__name__)
Expand All @@ -26,20 +26,12 @@ def change_password(new_password: str) -> str:
"repeat": new_password,
}

try:
config["GENESIS API"]["password"]
except KeyError as e:
raise KeyError(
"Password not found in config! Please make sure \
setup_credentials() was run properly & your user data is set correctly!",
) from e

# change remote password
response_text = load_data(
endpoint="profile", method="password", params=params
)
# change local password
set_db_pw(new_password)
db.set_db_pw(new_password)

logger.info("Password changed successfully!")

Expand Down
25 changes: 4 additions & 21 deletions tests/test_helloworld.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,25 @@


def test_whoami(mocker):
mocker.patch(
"pystatis.helloworld.load_config",
return_value={
"GENESIS API": {
"base_url": "mocked_url",
"username": "JaneDoe",
"password": "password",
}
},
)

mocker.patch(
"pystatis.helloworld.requests.get",
return_value=_generic_request_status(),
)
mocker.patch("pystatis.db.get_db_host", return_value="genesis")

response = whoami()

assert response == str(_generic_request_status().text)


def test_logincheck(mocker):
mocker.patch(
"pystatis.helloworld.load_config",
return_value={
"GENESIS API": {
"base_url": "mocked_url",
"username": "JaneDoe",
"password": "password",
}
},
)
mocker.patch(
"pystatis.helloworld.requests.get",
return_value=_generic_request_status(),
)
mocker.patch(
"pystatis.db.get_db_settings", return_value=("host", "user", "pw")
)

response = logincheck()

Expand Down
9 changes: 1 addition & 8 deletions tests/test_http_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,7 @@ def test_get_response_from_endpoint(mocker):
"pystatis.http_helper.requests", return_value=_generic_request_status()
)
mocker.patch(
"pystatis.http_helper.load_config",
return_value={
"GENESIS API": {
"base_url": "mocked_url",
"username": "JaneDoe",
"password": "password",
}
},
"pystatis.db.get_db_settings", return_value=("host", "user", "pw")
)

get_data_from_endpoint(endpoint="endpoint", method="method", params={})
Expand Down
55 changes: 14 additions & 41 deletions tests/test_profile.py
Original file line number Diff line number Diff line change
@@ -1,66 +1,39 @@
import re
from configparser import ConfigParser
from pathlib import Path

import pytest

from pystatis.profile import change_password, remove_result
from pystatis.config import init_config, load_config
from pystatis import db
from tests.test_http_helper import _generic_request_status


@pytest.fixture()
def cache_dir(tmp_path_factory):
def config_dir(tmp_path_factory) -> str:
# remove white-space and non-latin characters (issue fo some user names)
temp_dir = str(tmp_path_factory.mktemp(".pystatis"))
temp_dir = re.sub(r"[^\x00-\x7f]", r"", temp_dir.replace(" ", ""))

return Path(temp_dir)
return temp_dir


def test_change_password(mocker, cache_dir):
def test_change_password(mocker, config_dir):
# mock configparser to be able to test writing of new password
config = ConfigParser()
config["GENESIS API"] = {
"base_url": "mocked_url",
"username": "JaneDoe",
"password": "password",
}
mocker.patch("pystatis.profile.load_config", return_value=config)
mocker.patch(
"pystatis.profile.load_data",
return_value=str(_generic_request_status().text),
)
mocker.patch(
"pystatis.profile.get_config_path_from_settings",
return_value=cache_dir / "config.ini",
)

response = change_password("new_password")

assert response == str(_generic_request_status().text)
init_config(config_dir)
config = load_config()

assert config["genesis"]["password"] == ""

def test_change_password_keyerror(mocker, cache_dir):
# define empty config (no password)
mocker.patch(
"pystatis.profile.load_config", return_value={"GENESIS API": {}}
)
mocker.patch(
"pystatis.profile.load_data",
return_value=str(_generic_request_status().text),
)
mocker.patch(
"pystatis.profile.get_config_path_from_settings",
return_value=cache_dir / "config.ini",
return_value=_generic_request_status(),
)

with pytest.raises(KeyError) as e:
change_password("new_password")
assert (
"Password not found in config! Please make sure \
init_config() was run properly & your user data is set correctly!"
in str(e.value)
)
db.set_db("genesis")
response = change_password("new_password")
config = load_config()

assert config["genesis"]["password"] == "new_password"


def test_remove_result(mocker):
Expand Down

0 comments on commit 8fcddc0

Please sign in to comment.