Skip to content

load username and email #63

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/diffpy/labpdfproc/labpdfprocapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from diffpy.labpdfproc.functions import apply_corr, compute_cve
from diffpy.labpdfproc.tools import (
known_sources,
load_user_info,
load_user_metadata,
set_input_lists,
set_output_directory,
Expand Down Expand Up @@ -96,6 +97,7 @@ def get_args(override_cli_inputs=None):

def main():
args = get_args()
args = load_user_info(args)
args = set_input_lists(args)
args.output_directory = set_output_directory(args)
args.wavelength = set_wavelength(args)
Expand Down
7 changes: 7 additions & 0 deletions src/diffpy/labpdfproc/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
from pathlib import Path

import pytest
Expand All @@ -8,6 +9,8 @@ def user_filesystem(tmp_path):
base_dir = Path(tmp_path)
input_dir = base_dir / "input_dir"
input_dir.mkdir(parents=True, exist_ok=True)
conf_dir = base_dir / "conf_dir"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's call it home_dir instead of conf_dir to make the intent clearer.

conf_dir.mkdir(parents=True, exist_ok=True)

chi_data = "dataformat = twotheta\n mode = xray\n # chi_Q chi_I\n 1 2\n 3 4\n 5 6\n 7 8\n"
xy_data = "1 2\n 3 4\n 5 6\n 7 8"
Expand Down Expand Up @@ -44,4 +47,8 @@ def user_filesystem(tmp_path):
f.write("good_data.xy \n")
f.write(f"{str(input_dir.resolve() / 'good_data.txt')}\n")

user_config_data = {"username": "good_username", "email": "[email protected]"}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be home_user and [email protected]

with open(conf_dir / "diffpyconfig.json", "w") as f:
json.dump(user_config_data, f)

yield tmp_path
99 changes: 99 additions & 0 deletions src/diffpy/labpdfproc/tests/test_tools.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import os
import re
from pathlib import Path
Expand All @@ -7,6 +8,7 @@
from diffpy.labpdfproc.labpdfprocapp import get_args
from diffpy.labpdfproc.tools import (
known_sources,
load_user_info,
load_user_metadata,
set_input_lists,
set_output_directory,
Expand Down Expand Up @@ -241,3 +243,100 @@ def test_load_user_metadata_bad(inputs, msg):
actual_args = get_args(cli_inputs)
with pytest.raises(ValueError, match=msg[0]):
actual_args = load_user_metadata(actual_args)


params_user_info_without_conf_file = [
(["new_username", "[email protected]"], ["new_username", "[email protected]", "new_username", "[email protected]"]),
]


@pytest.mark.parametrize("inputs, expected", params_user_info_without_conf_file)
def test_load_user_info_without_conf_file(monkeypatch, inputs, expected, user_filesystem):
expected_args_username, expected_args_email, expected_conf_username, expected_conf_email = expected

os.chdir(user_filesystem)
input_user = iter(inputs)
monkeypatch.setattr("builtins.input", lambda _: next(input_user))
monkeypatch.setattr("diffpy.labpdfproc.user_config.HOME_CONFIG_PATH", user_filesystem / "diffpyconfig.json")

cli_inputs = ["2.5", "data.xy"]
actual_args = get_args(cli_inputs)
actual_args = load_user_info(actual_args)
assert actual_args.username == expected_args_username
assert actual_args.email == expected_args_email
with open(user_filesystem / "diffpyconfig.json", "r") as f:
config_data = json.load(f)
assert config_data == {"username": expected_conf_username, "email": expected_conf_email}


params_user_info_with_conf_file = [
(["", ""], ["good_username", "[email protected]", "good_username", "[email protected]"]),
(["new_username", ""], ["new_username", "[email protected]", "good_username", "[email protected]"]),
(["", "[email protected]"], ["good_username", "[email protected]", "good_username", "[email protected]"]),
(["new_username", "[email protected]"], ["new_username", "[email protected]", "good_username", "[email protected]"]),
]


@pytest.mark.parametrize("inputs, expected", params_user_info_with_conf_file)
def test_load_user_info_with_conf_file(monkeypatch, inputs, expected, user_filesystem):
expected_args_username, expected_args_email, expected_conf_username, expected_conf_email = expected
user_config_data = {"username": "good_username", "email": "[email protected]"}
with open(user_filesystem / "diffpyconfig.json", "w") as f:
json.dump(user_config_data, f)

# test it works when config file is in current directory
# check username and email are correctly loaded and config file is not modified
os.chdir(user_filesystem / "conf_dir")
input_user = iter(inputs)
monkeypatch.setattr("builtins.input", lambda _: next(input_user))
monkeypatch.setattr("diffpy.labpdfproc.user_config.HOME_CONFIG_PATH", user_filesystem / "diffpyconfig.json")

cli_inputs = ["2.5", "data.xy"]
actual_args = get_args(cli_inputs)
actual_args = load_user_info(actual_args)
assert actual_args.username == expected_args_username
assert actual_args.email == expected_args_email
with open(Path.cwd() / "diffpyconfig.json", "r") as f:
config_data = json.load(f)
assert config_data == {"username": expected_conf_username, "email": expected_conf_email}

# test it works when config file is in home directory and not in current directory new_dir
# check username and email are correctly loaded and config file is not modified
new_dir = user_filesystem / "new_dir"
new_dir.mkdir(parents=True, exist_ok=True)
os.chdir(new_dir)
input_user = iter(inputs)
monkeypatch.setattr("builtins.input", lambda _: next(input_user))

cli_inputs = ["2.5", "data.xy"]
actual_args = get_args(cli_inputs)
actual_args = load_user_info(actual_args)
assert actual_args.username == expected_args_username
assert actual_args.email == expected_args_email
with open(user_filesystem / "diffpyconfig.json", "r") as f:
config_data = json.load(f)
assert config_data == {"username": expected_conf_username, "email": expected_conf_email}


params_user_info_bad = [
# No valid username/email in config file (or no config file),
# and user didn't enter username/email the first time they were asked
(["", ""], "Please rerun the program and provide a username and email."),
(["", "[email protected]"], "Please rerun the program and provide a username."),
(["good_username", ""], "Please rerun the program and provide an email."),
# User entered an invalid email
(["good_username", "bad_email"], "Please rerun the program and provide a valid email."),
]


@pytest.mark.parametrize("inputs, msg", params_user_info_bad)
def test_load_user_info_bad(monkeypatch, inputs, msg, user_filesystem):
os.chdir(user_filesystem)
input_user = iter(inputs)
monkeypatch.setattr("builtins.input", lambda _: next(input_user))
monkeypatch.setattr("diffpy.labpdfproc.user_config.HOME_CONFIG_PATH", user_filesystem / "diffpyconfig.json")

cli_inputs = ["2.5", "data.xy"]
actual_args = get_args(cli_inputs)
with pytest.raises(ValueError, match=msg[0]):
actual_args = load_user_info(actual_args)
46 changes: 46 additions & 0 deletions src/diffpy/labpdfproc/tools.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from pathlib import Path

from diffpy.labpdfproc.user_config import prompt_user_info, read_conf_file, write_conf_file

WAVELENGTHS = {"Mo": 0.71, "Ag": 0.59, "Cu": 1.54}
known_sources = [key for key in WAVELENGTHS.keys()]

Expand Down Expand Up @@ -171,3 +173,47 @@ def load_user_metadata(args):
setattr(args, key, value)
delattr(args, "user_metadata")
return args


def load_user_info(args):
"""
Load username and email into args.

Prompt the user to enter username and email.
If not provided, read from the config file (first from cwd, and then from home directory).
If neither are available, raise a ValueError.
Save provided values to the config file if a config file doesn't exist.

Parameters
----------
args argparse.Namespace
the arguments from the parser

Returns
-------
the updated argparse Namespace with username and email

"""
input_username, input_email = prompt_user_info()
conf_username, conf_email = read_conf_file()

no_username = not input_username and not conf_username
no_email = not input_email and not conf_email
if no_username and no_email:
raise ValueError("Please rerun the program and provide a username and email.")
if no_username:
raise ValueError("Please rerun the program and provide a username.")
if no_email:
raise ValueError("Please rerun the program and provide an email.")

username = input_username or conf_username
email = input_email or conf_email
if "@" not in email:
raise ValueError("Please rerun the program and provide a valid email.")

setattr(args, "username", username)
setattr(args, "email", email)

if not conf_username and not conf_email:
write_conf_file(username, email)
return args
34 changes: 34 additions & 0 deletions src/diffpy/labpdfproc/user_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import json
from pathlib import Path

CONFIG_FILE = "diffpyconfig.json"
CWD_CONFIG_PATH = Path.cwd() / CONFIG_FILE
HOME_CONFIG_PATH = Path.home() / CONFIG_FILE


def prompt_user_info():
username = input("Please enter your username (or press Enter to skip if you already entered before): ")
email = input("Please enter your email (or press Enter to skip if you already entered before): ")
return username, email


def find_conf_file():
if CWD_CONFIG_PATH.exists() and CWD_CONFIG_PATH.is_file():
return CWD_CONFIG_PATH
elif HOME_CONFIG_PATH.exists() and HOME_CONFIG_PATH.is_file():
return HOME_CONFIG_PATH
return None


def read_conf_file():
conf_file = find_conf_file()
if conf_file:
with open(conf_file, "r") as f:
config = json.load(f)
return config.get("username"), config.get("email")
return None, None


def write_conf_file(username, email):
with open(HOME_CONFIG_PATH, "w") as f:
json.dump({"username": username, "email": email}, f)
Loading