Skip to content

Commit 4c0deba

Browse files
authored
Merge pull request #108 from GeoscienceAustralia/NPI-4443-unittest-cleanup
NPI-4443 Clean up unit test outputs and temporarily pin supported Pandas version
2 parents 0fa9d8d + 37ba98e commit 4c0deba

11 files changed

Lines changed: 300 additions & 136 deletions

File tree

gnssanalysis/filenames.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def determine_file_name_main(
134134
else:
135135
print(new_name)
136136
except NotImplementedError:
137-
logging.warning(f"Skipping {f.name} as {f.suffix} files are not yet supported.")
137+
warnings.warn(f"Skipping {f.name} as {f.suffix} files are not yet supported.")
138138

139139

140140
def determine_file_name(
@@ -542,8 +542,8 @@ def determine_clk_name_props(file_path: pathlib.Path) -> dict[str, Any]:
542542
except Exception as e:
543543
# TODO: Work out what exceptions read_clk can actually throw when given a non-CLK file
544544
# At the moment we will also swallow errors we really shouldn't
545-
logging.warning(f"{file_path.name} can't be read as an CLK file. Defaulting properties.")
546-
logging.warning(f"Exception {e}, {type(e)}")
545+
warnings.warn(f"{file_path.name} can't be read as an CLK file. Defaulting properties.")
546+
warnings.warn(f"Exception {e}, {type(e)}")
547547
logging.info(traceback.format_exc())
548548
return {}
549549
return name_props
@@ -597,8 +597,8 @@ def determine_erp_name_props(file_path: pathlib.Path) -> dict[str, Any]:
597597
except Exception as e:
598598
# TODO: Work out what exceptions read_erp can actually throw when given a non-ERP file
599599
# At the moment we will also swallow errors we really shouldn't
600-
logging.warning(f"{file_path.name} can't be read as an ERP file. Defaulting properties.")
601-
logging.warning(f"Exception {e}, {type(e)}")
600+
warnings.warn(f"{file_path.name} can't be read as an ERP file. Defaulting properties.")
601+
warnings.warn(f"Exception {e}, {type(e)}")
602602
logging.info(traceback.format_exc())
603603
return {}
604604
return name_props
@@ -689,8 +689,8 @@ def determine_snx_name_props(file_path: pathlib.Path) -> dict[str, Any]:
689689
except Exception as e:
690690
# TODO: Work out what exceptions _get_snx_vector can actually throw when given a non-SNX file
691691
# At the moment we will also swallow errors we really shouldn't
692-
logging.warning(f"{file_path.name} can't be read as an SNX file. Defaulting properties.")
693-
logging.warning(f"Exception {e}, {type(e)}")
692+
warnings.warn(f"{file_path.name} can't be read as an SNX file. Defaulting properties.")
693+
warnings.warn(f"Exception {e}, {type(e)}")
694694
logging.info(traceback.format_exc())
695695
return {}
696696
return name_props
@@ -1015,7 +1015,7 @@ def check_filename_and_contents_consistency(
10151015
# If parsing of a long filename fails, Project will not be present. In this case we have with minimal (and
10161016
# maybe incorrect) properties to compare. So we raise a warning.
10171017
if "project" not in file_name_properties:
1018-
logging.warning(
1018+
warnings.warn(
10191019
f"Failed to parse filename according to the long filename format: '{input_file.name}'. "
10201020
"As a result few useful properties are available to compare with the file contents, so the "
10211021
"detailed consistency check will be skipped!"
@@ -1027,17 +1027,19 @@ def check_filename_and_contents_consistency(
10271027

10281028
contents_epoch_interval = file_content_properties.get("sampling_rate_seconds", None)
10291029
if contents_epoch_interval is None:
1030-
logging.warning(
1030+
warnings.warn(
10311031
f"Sampling rate couldn't be inferred from file contents '{input_file.name}'. "
10321032
"Cannot allow for timespan discrepancies of one epoch interval, so an error may follow."
10331033
)
10341034

10351035
discrepancies = {}
10361036
# Check for keys only present on one side
10371037
orphan_keys = set(file_name_properties.keys()).symmetric_difference((set(file_content_properties.keys())))
1038-
logging.warning(
1038+
orphan_keys_sorted = list(orphan_keys)
1039+
orphan_keys_sorted.sort()
1040+
warnings.warn(
10391041
"The following properties can't be compared, as they were extracted only from file content or "
1040-
f"name (not both): {str(orphan_keys)}"
1042+
f"name (not both): {str(orphan_keys_sorted)}"
10411043
)
10421044
if output_orphan_prop_names:
10431045
# Output properties found only in content OR filename.

gnssanalysis/gn_diffaux.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import logging as _logging
22
from pathlib import Path as _Path
33
from typing import Literal, Union
4+
import warnings
45

56
import numpy as _np
67
import pandas as _pd
@@ -118,7 +119,7 @@ def _compare_states(diffstd: _pd.DataFrame, log_lvl: int, tol: Union[float, None
118119
diff_states = diffstd.unstack(["TYPE", "SITE", "SAT", "BLK", "NUM"])
119120
# we remove the '.droplevel("NUM", axis=0)' due to ORBIT_PTS non-uniqueness. Changing to ORBIT_PTS_blah might be a better solution
120121
if diff_states.empty:
121-
_logging.warning(msg=f":diffutil states not present. Skipping")
122+
warnings.warn(f":diffutil states not present. Skipping")
122123
return 0
123124
if plot:
124125
# a standard scatter plot
@@ -157,7 +158,7 @@ def _compare_residuals(diffstd: _pd.DataFrame, log_lvl: int, tol: Union[float, N
157158
idx_names_to_unstack.remove("TIME") # all but TIME: ['SITE', 'TYPE', 'SAT', 'NUM', 'It', 'BLK']
158159
diff_residuals = diffstd.unstack(idx_names_to_unstack)
159160
if diff_residuals.empty:
160-
_logging.warning(f":diffutil residuals not present. Skipping")
161+
warnings.warn(f":diffutil residuals not present. Skipping")
161162
return 0
162163
bad_residuals = _diff2msg(diff_residuals, tol=tol)
163164
if bad_residuals is not None:
@@ -176,7 +177,7 @@ def _compare_residuals(diffstd: _pd.DataFrame, log_lvl: int, tol: Union[float, N
176177
def _compare_stec(diffstd, log_lvl, tol=None):
177178
stec_diff = diffstd.unstack(level=("SITE", "SAT", "LAYER"))
178179
if stec_diff.empty:
179-
_logging.warning(f":diffutil stec states not present. Skipping")
180+
warnings.warn(f":diffutil stec states not present. Skipping")
180181
return 0
181182
bad_sv_states = _diff2msg(stec_diff, tol, dt_as_gpsweek=True)
182183
if bad_sv_states is not None:
@@ -323,7 +324,7 @@ def compare_clk(
323324
clk_b: baseline (normally b is test)
324325
"""
325326

326-
_logging.warning(
327+
warnings.warn(
327328
"compare_clk() is deprecated. Please use diff_clk() and note that the clk inputs are in opposite order"
328329
)
329330
return diff_clk(clk_baseline=clk_b, clk_test=clk_a, norm_types=norm_types, ext_dt=ext_dt, ext_svs=ext_svs)
@@ -428,7 +429,7 @@ def sisre(
428429
DEPRECATED
429430
"""
430431

431-
_logging.warning(
432+
warnings.warn(
432433
"sisre() is deprecated, please use calculate_sisre() instead. Note that input arg test/baseline orders are flipped"
433434
)
434435
return calculate_sisre(

gnssanalysis/gn_download.py

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -94,12 +94,11 @@ def __call__(self, bytes_transferred):
9494
_sys.stdout.flush()
9595

9696

97-
98-
def get_earthdata_credentials(username: str = None, password: str = None) -> Tuple[str, str]:
97+
def get_earthdata_credentials(username: Optional[str] = None, password: Optional[str] = None) -> Tuple[str, str]:
9998
"""
10099
Get NASA Earthdata credentials from .netrc file or direct parameters.
101-
:param str username: Directly provided username (highest priority)
102-
:param str password: Directly provided password (highest priority)
100+
:param Optional[str] username: Directly provided username (highest priority)
101+
:param Optional[str] password: Directly provided password (highest priority)
103102
:return Tuple[str, str]: Username and password tuple
104103
:raises ValueError: If no credentials can be obtained
105104
"""
@@ -774,17 +773,17 @@ def ftp_tls(url: str, **kwargs) -> Generator[Any, Any, Any]:
774773

775774
def download_file_from_cddis(
776775
filename: str,
777-
ftp_folder: Optional[str] = None, # deprecated
778-
url_folder: Optional[str] = None, # preferred
776+
ftp_folder: Optional[str] = None, # deprecated
777+
url_folder: Optional[str] = None, # preferred
779778
output_folder: _Path = _Path("."),
780779
max_retries: int = 3,
781780
decompress: bool = True,
782781
if_file_present: str = "prompt_user",
783-
username: str = None,
784-
password: str = None,
782+
username: Optional[str] = None,
783+
password: Optional[str] = None,
785784
note_filetype: Optional[str] = None,
786785
) -> Union[_Path, None]:
787-
""" Download a single file from the CDDIS HTTPS archive using NASA Earthdata authentication
786+
"""Download a single file from the CDDIS HTTPS archive using NASA Earthdata authentication
788787
789788
:param str filename: Name of the file to download
790789
:param str ftp_folder: (Deprecated) Legacy folder path on the CDDIS FTP server. Use url_folder instead
@@ -794,8 +793,8 @@ def download_file_from_cddis(
794793
:param bool decompress: If true, decompresses files on download, defaults to True
795794
:param str if_file_present: What to do if file already present: "replace", "dont_replace", defaults to "prompt_user"
796795
:param str note_filetype: How to label the file for STDOUT messages, defaults to None
797-
:param str username: NASA Earthdata username (optional, will try .netrc if not provided).
798-
:param str password: NASA Earthdata password (optional, will try .netrc if not provided).
796+
:param Optional[str] username: NASA Earthdata username (optional, will try .netrc if not provided).
797+
:param Optional[str] password: NASA Earthdata password (optional, will try .netrc if not provided).
799798
:raises ValueError: If no credentials can be obtained.
800799
:raises requests.RequestException: If the file cannot be downloaded after retries.
801800
:return _Path or None: The pathlib.Path of the downloaded file (or decompressed output of it).
@@ -823,14 +822,8 @@ def download_file_from_cddis(
823822
if download_filepath is None:
824823
return None # File exists and user chose not to replace
825824

826-
# Get NASA Earthdata credentials
827-
try:
828-
earthdata_username, earthdata_password = get_earthdata_credentials(
829-
username=username, password=password
830-
)
831-
except ValueError as e:
832-
logging.error(f"Failed to obtain NASA Earthdata credentials: {e}")
833-
raise
825+
# Get NASA Earthdata credentials (raises ValueError on failure)
826+
earthdata_username, earthdata_password = get_earthdata_credentials(username=username, password=password)
834827

835828
retries = 0
836829
while retries <= max_retries:
@@ -862,25 +855,27 @@ def download_file_from_cddis(
862855
except _requests.exceptions.RequestException as e:
863856
retries += 1
864857
if retries > max_retries:
858+
# TODO consider wrapping the RequestException with this, and raising that, rather than logging an error
865859
logging.error(f"Failed to download {filename} after {max_retries} retries: {e}")
866860
if download_filepath.is_file():
867861
download_filepath.unlink()
868862
raise
869863
backoff = _random.uniform(0.0, 2.0 ** retries)
870-
logging.warning(f"Error downloading {filename}: {e} "
871-
f"(retry {retries}/{max_retries}, backoff {backoff:.1f}s)")
864+
_warnings.warn(
865+
f"Error downloading {filename}: {e} " f"(retry {retries}/{max_retries}, backoff {backoff:.1f}s)"
866+
)
872867
_time.sleep(backoff)
873868

874869
raise Exception("Unexpected fallthrough in download_file_from_cddis.")
875870

876871

877872
def download_multiple_files_from_cddis(
878873
files: List[str],
879-
ftp_folder: Optional[str] = None, # deprecated
880-
url_folder: Optional[str] = None, # preferred
874+
ftp_folder: Optional[str] = None, # deprecated
875+
url_folder: Optional[str] = None, # preferred
881876
output_folder: _Path = _Path("."),
882-
username: str = None,
883-
password: str = None,
877+
username: Optional[str] = None,
878+
password: Optional[str] = None,
884879
) -> None:
885880
"""
886881
Download multiple files from the CDDIS HTTPS archive concurrently, using a thread pool.
@@ -889,8 +884,8 @@ def download_multiple_files_from_cddis(
889884
:param str ftp_folder: (Deprecated) Legacy folder path on the CDDIS FTP server. Use url_folder instead.
890885
:param str url_folder: Folder path (relative to CDDIS HTTPS archive root).
891886
:param _Path output_folder: Local folder to store the output files.
892-
:param str username: NASA Earthdata username (optional, will try .netrc if not provided).
893-
:param str password: NASA Earthdata password (optional, will try .netrc if not provided).
887+
:param Optional[str] username: NASA Earthdata username (optional, will try .netrc if not provided).
888+
:param Optional[str] password: NASA Earthdata password (optional, will try .netrc if not provided).
894889
:raises ValueError: If both ftp_folder and url_folder are provided.
895890
:return None: Runs downloads in parallel, does not return values. Each file is handled independently.
896891
"""
@@ -943,8 +938,8 @@ def download_product_from_cddis(
943938
project_type: str = "OPS",
944939
timespan: _datetime.timedelta = _datetime.timedelta(days=2),
945940
if_file_present: str = "prompt_user",
946-
username: str = None,
947-
password: str = None,
941+
username: Optional[str] = None,
942+
password: Optional[str] = None,
948943
) -> List[_Path]:
949944
"""Download the file/s from CDDIS based on start and end epoch, to the download directory (download_dir)
950945
@@ -961,8 +956,8 @@ def download_product_from_cddis(
961956
:param str project_type: Project type of file to download (e.g. ), defaults to "OPS"
962957
:param _datetime.timedelta timespan: Timespan of the file/s to download, defaults to _datetime.timedelta(days=2)
963958
:param str if_file_present: What to do if file already present: "replace", "dont_replace", defaults to "prompt_user"
964-
:param str username: NASA Earthdata username (optional, will try .netrc if not provided).
965-
:param str password: NASA Earthdata password (optional, will try .netrc if not provided).
959+
:param Optional[str] username: NASA Earthdata username (optional, will try .netrc if not provided).
960+
:param Optional[str] password: NASA Earthdata password (optional, will try .netrc if not provided).
966961
:raises FileNotFoundError: Raise error if the specified file cannot be found on CDDIS
967962
:raises Exception: If a file fails to download after all retries.
968963
:return List[_Path]: List of pathlib.Path objects to downloaded (or decompressed) files.

0 commit comments

Comments
 (0)