Skip to content

Commit c2a838e

Browse files
added tests for UC1 and UC4, rewrite function to overwrite config file data with user inputs
1 parent 33a0bd2 commit c2a838e

File tree

4 files changed

+127
-40
lines changed

4 files changed

+127
-40
lines changed

src/diffpy/labpdfproc/tests/conftest.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
from pathlib import Path
23

34
import pytest
@@ -8,6 +9,8 @@ def user_filesystem(tmp_path):
89
base_dir = Path(tmp_path)
910
input_dir = base_dir / "input_dir"
1011
input_dir.mkdir(parents=True, exist_ok=True)
12+
conf_dir = base_dir / "conf_dir"
13+
conf_dir.mkdir(parents=True, exist_ok=True)
1114

1215
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"
1316
xy_data = "1 2\n 3 4\n 5 6\n 7 8"
@@ -44,4 +47,10 @@ def user_filesystem(tmp_path):
4447
f.write("good_data.xy \n")
4548
f.write(f"{str(input_dir.resolve() / 'good_data.txt')}\n")
4649

50+
user_config_data = {"username": "good_username", "email": "[email protected]"}
51+
with open(conf_dir / "test.json", "w") as f:
52+
json.dump(user_config_data, f)
53+
with open(conf_dir / "test2.json", "w") as f:
54+
json.dump({}, f)
55+
4756
yield tmp_path

src/diffpy/labpdfproc/tests/test_tools.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
import os
23
import re
34
from pathlib import Path
@@ -7,6 +8,7 @@
78
from diffpy.labpdfproc.labpdfprocapp import get_args
89
from diffpy.labpdfproc.tools import (
910
known_sources,
11+
load_user_info,
1012
load_user_metadata,
1113
set_input_lists,
1214
set_output_directory,
@@ -241,3 +243,65 @@ def test_load_user_metadata_bad(inputs, msg):
241243
actual_args = get_args(cli_inputs)
242244
with pytest.raises(ValueError, match=msg[0]):
243245
actual_args = load_user_metadata(actual_args)
246+
247+
248+
# For each test case, check username and email are properly loaded and written into config file
249+
params_user_info = [
250+
# No existing config file, user enters valid username and email
251+
(["good_username", "[email protected]", "non_existing_file.json"], ["good_username", "[email protected]"]),
252+
# There exists a config file, so we read it and fetch info, no user input is fine
253+
(["", "", "test.json"], ["good_username", "[email protected]"]),
254+
# There exists a config file, user input username/email overwrites the username/email in the file
255+
(["new_username", "", "test.json"], ["new_username", "[email protected]"]),
256+
(["", "[email protected]", "test.json"], ["good_username", "[email protected]"]),
257+
(["new_username", "[email protected]", "test.json"], ["new_username", "[email protected]"]),
258+
# There exists a config file that does not contain username/email, then we write user inputs into config file
259+
(["good_username", "[email protected]", "test2.json"], ["good_username", "[email protected]"]),
260+
]
261+
262+
263+
@pytest.mark.parametrize("inputs, expected", params_user_info)
264+
def test_load_user_info(monkeypatch, inputs, expected, user_filesystem):
265+
os.chdir(user_filesystem / "conf_dir")
266+
expected_username, expected_email = expected
267+
input_username, input_email, input_config_file = inputs
268+
mock_prompt_user_info = iter([input_username, input_email])
269+
monkeypatch.setattr("builtins.input", lambda _: next(mock_prompt_user_info))
270+
271+
cli_inputs = ["2.5", "data.xy"]
272+
actual_args = get_args(cli_inputs)
273+
actual_args = load_user_info(actual_args, input_config_file)
274+
275+
assert actual_args.username == expected_username
276+
assert actual_args.email == expected_email
277+
with open(input_config_file, "r") as f:
278+
config_data = json.load(f)
279+
assert config_data == {"username": expected_username, "email": expected_email}
280+
281+
282+
params_user_info_bad = [
283+
# No valid username/email in config file (or no config file),
284+
# and user didn't enter username/email the first time they were asked
285+
(["", "", "non_existing_file.json"], "Please rerun the program and provide a username and email."),
286+
(["", "[email protected]", "non_existing_file.json"], "Please rerun the program and provide a username."),
287+
(["good_username", "", "non_existing_file.json"], "Please rerun the program and provide an email."),
288+
# User entered an invalid email
289+
(
290+
["good_username", "bad_email", "non_existing_file.json"],
291+
"Please rerun the program and provide a valid email.",
292+
),
293+
(["good_username", "bad_email", "test.json"], "Please rerun the program and provide a valid email."),
294+
]
295+
296+
297+
@pytest.mark.parametrize("inputs, msg", params_user_info_bad)
298+
def test_load_user_info_bad(monkeypatch, inputs, msg, user_filesystem):
299+
os.chdir(user_filesystem)
300+
input_username, input_email, input_config_file = inputs
301+
mock_prompt_user_info = iter([input_username, input_email])
302+
monkeypatch.setattr("builtins.input", lambda _: next(mock_prompt_user_info))
303+
304+
cli_inputs = ["2.5", "data.xy"]
305+
actual_args = get_args(cli_inputs)
306+
with pytest.raises(ValueError, match=msg[0]):
307+
actual_args = load_user_info(actual_args, config_file=input_config_file)

src/diffpy/labpdfproc/tools.py

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from pathlib import Path
22

3-
from diffpy.labpdfproc.user_config import find_conf_file, read_conf_file, user_info_conf
3+
from diffpy.labpdfproc.user_config import CONFIG_FILE, prompt_user_info, read_conf_file, write_conf_file
44

55
WAVELENGTHS = {"Mo": 0.71, "Ag": 0.59, "Cu": 1.54}
66
known_sources = [key for key in WAVELENGTHS.keys()]
@@ -175,15 +175,42 @@ def load_user_metadata(args):
175175
return args
176176

177177

178-
def load_user_info(args):
179-
conf_file_path = find_conf_file()
180-
if conf_file_path is not None:
181-
conf_file = read_conf_file(conf_file_path)
182-
if "username" in conf_file and "useremail" in conf_file:
183-
setattr(args, "username", conf_file["username"])
184-
setattr(args, "useremail", conf_file["useremail"])
185-
return args
186-
else:
187-
return user_info_conf(args)
188-
else:
189-
return user_info_conf(args)
178+
def load_user_info(args, config_file=CONFIG_FILE):
179+
"""
180+
Load username and email into args.
181+
182+
Prompt the user to enter username and email. If not provided, read from the config file.
183+
If neither are available, raise a ValueError.
184+
Save provided values to the config file (overwriting existing values if needed).
185+
186+
Parameters
187+
----------
188+
args argparse.Namespace
189+
the arguments from the parser
190+
191+
Returns
192+
-------
193+
the updated argparse Namespace with username and email
194+
195+
"""
196+
input_username, input_email = prompt_user_info()
197+
conf_username, conf_email = read_conf_file(config_file)
198+
199+
no_username = not input_username and not conf_username
200+
no_email = not input_email and not conf_email
201+
if no_username and no_email:
202+
raise ValueError("Please rerun the program and provide a username and email.")
203+
if no_username:
204+
raise ValueError("Please rerun the program and provide a username.")
205+
if no_email:
206+
raise ValueError("Please rerun the program and provide an email.")
207+
208+
username = input_username or conf_username
209+
email = input_email or conf_email
210+
if "@" not in email:
211+
raise ValueError("Please rerun the program and provide a valid email.")
212+
213+
setattr(args, "username", username)
214+
setattr(args, "email", email)
215+
write_conf_file(username, email, config_file)
216+
return args

src/diffpy/labpdfproc/user_config.py

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,24 @@
11
import json
2-
import os
32
from pathlib import Path
43

54
CONFIG_FILE = "labpdfprocconfig.json"
65

76

8-
def find_conf_file():
9-
# Return config file path if such a file exists
10-
if os.path.exists(CONFIG_FILE):
11-
return Path(CONFIG_FILE).resolve()
12-
return None
13-
14-
15-
def read_conf_file(file_path):
16-
with open(file_path, "r") as f:
17-
return json.load(f)
18-
19-
20-
def write_conf_file(file_path, username, useremail):
21-
config = {"username": username, "useremail": useremail}
22-
with open(file_path, "w") as f:
23-
json.dump(config, f)
7+
def prompt_user_info():
8+
username = input("Please enter your username (or press Enter to skip if you already entered before): ")
9+
email = input("Please enter your email (or press Enter to skip if you already entered before): ")
10+
return username, email
2411

2512

26-
def prompt_user_info():
27-
username = input("Please enter your username (or press Enter to skip): ")
28-
useremail = input("Please enter your email (or press Enter to skip): ")
29-
return username, useremail
13+
def read_conf_file(config_file=CONFIG_FILE):
14+
config_path = Path(config_file).resolve()
15+
if config_path.exists() and config_path.is_file():
16+
with open(config_file, "r") as f:
17+
config = json.load(f)
18+
return config.get("username"), config.get("email")
19+
return None, None
3020

3121

32-
def user_info_conf(args):
33-
username, useremail = prompt_user_info()
34-
write_conf_file(CONFIG_FILE, username, useremail)
35-
setattr(args, "username", username)
36-
setattr(args, "useremail", useremail)
37-
return args
22+
def write_conf_file(username, email, config_file=CONFIG_FILE):
23+
with open(config_file, "w") as f:
24+
json.dump({"username": username, "email": email}, f)

0 commit comments

Comments
 (0)