diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8f0dd535..0e14e97f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,6 @@ jobs: with: os: ${{ matrix.os }} python-version: "3.10" - secrets: inherit find-scripts: runs-on: ubuntu-latest @@ -55,5 +54,3 @@ jobs: - name: Run script run: python ${{ matrix.script }} - env: - MP_API_KEY: ${{ secrets.MP_API_KEY }} diff --git a/examples/make_assets/structure_viz.py b/examples/make_assets/structure_viz.py index 0f4b226b..17155534 100644 --- a/examples/make_assets/structure_viz.py +++ b/examples/make_assets/structure_viz.py @@ -1,4 +1,5 @@ # %% +import os from typing import cast import matplotlib.pyplot as plt @@ -8,10 +9,9 @@ import pymatviz as pmv from pymatviz.enums import ElemColorScheme, Key +from pymatviz.utils import TEST_FILES -struct: Structure # for type hinting - df_steels = load_dataset("matbench_steels") df_phonons = load_dataset("matbench_phonons") @@ -31,12 +31,26 @@ # %% Plot some disordered structures in 2D -disordered_structs = { - mp_id: MPRester().get_structure_by_material_id(mp_id, conventional_unit_cell=True) - for mp_id in ["mp-19017", "mp-12712"] -} +struct_mp_ids = ("mp-19017", "mp-12712") +structure_dir = f"{TEST_FILES}/structures" + +os.makedirs(structure_dir, exist_ok=True) +for mp_id in struct_mp_ids: + struct_file = f"{structure_dir}/{mp_id}.json.gz" + if not os.path.isfile(struct_file): + if os.getenv("CI"): + raise FileNotFoundError( + f"structure for {mp_id} not found, run this script locally to fetch it." + ) + + struct: Structure = MPRester().get_structure_by_material_id( + mp_id, conventional_unit_cell=True + ) + struct.to_file(struct_file) + + else: + struct = Structure.from_file(f"{structure_dir}/{mp_id}.json.gz") -for mp_id, struct in disordered_structs.items(): for site in struct: # disorder structures in-place if "Fe" in site.species: site.species = {"Fe": 0.4, "C": 0.4, "Mn": 0.2} diff --git a/tests/conftest.py b/tests/conftest.py index 9dac2013..cc4cd847 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -17,9 +17,9 @@ from collections.abc import Generator -# if platform is windows, set matplotlib backend to "Agg" to fix -# _tkinter.TclError: Can't find a usable init.tcl in the following directories -# https://github.com/orgs/community/discussions/26434 +# If platform is Windows, set matplotlib backend to "Agg" to fix: +# "_tkinter.TclError: Can't find a usable init.tcl in the following directories" +# See: https://github.com/orgs/community/discussions/26434 if platform.system() == "Windows": import matplotlib as mpl @@ -52,10 +52,10 @@ def df_or_arrays(request: pytest.FixtureRequest) -> DfOrArrays: @pytest.fixture(autouse=True) def _run_around_tests() -> Generator[None, None, None]: - """Ensure matplotlib plots are closed after each test so as not to leak state - between tests.""" + """Ensure matplotlib plots are closed after each test + so as not to leak state between tests. + """ # runs before each test - yield # runs after each test @@ -121,7 +121,7 @@ def matplotlib_scatter() -> plt.Figure: @pytest.fixture def glass_formulas() -> list[str]: - """First 20 materials in the Matbench glass dataset. + """First 20 materials in the MatBench glass dataset. from matminer.datasets import load_dataset diff --git a/tests/files/structures/mp-12712.json.gz b/tests/files/structures/mp-12712.json.gz new file mode 100644 index 00000000..78f64f34 Binary files /dev/null and b/tests/files/structures/mp-12712.json.gz differ diff --git a/tests/files/structures/mp-19017.json.gz b/tests/files/structures/mp-19017.json.gz new file mode 100644 index 00000000..06a0b209 Binary files /dev/null and b/tests/files/structures/mp-19017.json.gz differ diff --git a/tests/test_bar.py b/tests/test_bar.py index 77ff5362..c97cfbef 100644 --- a/tests/test_bar.py +++ b/tests/test_bar.py @@ -9,7 +9,6 @@ from pymatviz.bar import spacegroup_bar from pymatviz.utils import BACKENDS, MATPLOTLIB, PLOTLY -from tests.conftest import y_pred, y_true if TYPE_CHECKING: @@ -20,9 +19,6 @@ from pymatviz.utils import Backend -y_std_mock = y_true - y_pred - - @pytest.mark.parametrize("backend", BACKENDS) @pytest.mark.parametrize( ("xticks", "show_counts", "show_empty_bins", "log"), diff --git a/tests/test_io.py b/tests/test_io.py index 9f1c6813..9bc50db1 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -9,7 +9,6 @@ from unittest.mock import patch from xml.etree import ElementTree as ET -import pandas as pd import plotly.graph_objects as go import pytest from matplotlib import pyplot as plt diff --git a/tests/test_scatter.py b/tests/test_scatter.py index 47c1399b..6da9c064 100644 --- a/tests/test_scatter.py +++ b/tests/test_scatter.py @@ -26,8 +26,8 @@ from tests.conftest import DfOrArrays -x_col, y_col, *_ = df_regr -df_tips = px.data.tips() +X_COL, Y_COL, *_ = df_regr +DF_TIPS = px.data.tips() @pytest.mark.parametrize("log_density", [True, False]) @@ -166,7 +166,7 @@ def test_density_scatter_plotly( def test_density_scatter_plotly_hover_template() -> None: - fig = density_scatter_plotly(df=df_regr, x=x_col, y=y_col, log_density=True) + fig = density_scatter_plotly(df=df_regr, x=X_COL, y=Y_COL, log_density=True) hover_template = fig.data[0].hovertemplate assert "Point Density" in hover_template assert "color" not in hover_template # Ensure log-count values are not displayed @@ -175,18 +175,18 @@ def test_density_scatter_plotly_hover_template() -> None: @pytest.mark.parametrize("stats", [1, (1,), "foo"]) def test_density_scatter_plotly_raises_on_bad_stats_type(stats: Any) -> None: with pytest.raises(TypeError, match="stats must be bool or dict"): - density_scatter_plotly(df=df_regr, x=x_col, y=y_col, stats=stats) + density_scatter_plotly(df=df_regr, x=X_COL, y=Y_COL, stats=stats) def test_density_scatter_plotly_empty_dataframe() -> None: - empty_df = pd.DataFrame({x_col: [], y_col: []}) + empty_df = pd.DataFrame({X_COL: [], Y_COL: []}) with pytest.raises(ValueError, match="input should have multiple elements"): - density_scatter_plotly(df=empty_df, x=x_col, y=y_col) + density_scatter_plotly(df=empty_df, x=X_COL, y=Y_COL) def test_density_scatter_plotly_facet() -> None: fig = density_scatter_plotly( - df=df_tips, x="total_bill", y="tip", facet_col="smoker" + df=DF_TIPS, x="total_bill", y="tip", facet_col="smoker" ) assert isinstance(fig, go.Figure) @@ -196,7 +196,7 @@ def test_density_scatter_plotly_facet() -> None: def test_density_scatter_plotly_facet_log_density() -> None: fig = density_scatter_plotly( - df=df_tips, x="total_bill", y="tip", facet_col="smoker", log_density=True + df=DF_TIPS, x="total_bill", y="tip", facet_col="smoker", log_density=True ) assert fig.layout.coloraxis.colorbar.ticktext is not None @@ -205,7 +205,7 @@ def test_density_scatter_plotly_facet_log_density() -> None: def test_density_scatter_plotly_facet_stats() -> None: fig = density_scatter_plotly( - df=df_tips, x="total_bill", y="tip", facet_col="smoker", stats=True + df=DF_TIPS, x="total_bill", y="tip", facet_col="smoker", stats=True ) # Check there are at least 2 annotations (could be more due to facet labels) @@ -217,7 +217,7 @@ def test_density_scatter_plotly_facet_stats() -> None: def test_density_scatter_plotly_facet_best_fit_line() -> None: fig = density_scatter_plotly( - df=df_tips, x="total_bill", y="tip", facet_col="smoker", best_fit_line=True + df=DF_TIPS, x="total_bill", y="tip", facet_col="smoker", best_fit_line=True ) # Check there are at least 4 shapes (2 identity lines, 2 best fit lines) @@ -231,18 +231,18 @@ def test_density_scatter_plotly_facet_best_fit_line() -> None: def test_density_scatter_plotly_facet_custom_bins() -> None: fig = density_scatter_plotly( - df=df_tips, x="total_bill", y="tip", facet_col="smoker", n_bins=10 + df=DF_TIPS, x="total_bill", y="tip", facet_col="smoker", n_bins=10 ) # Check that binning has been applied (number of points should be reduced) - smoker_count = df_tips["smoker"].value_counts() + smoker_count = DF_TIPS["smoker"].value_counts() assert len(fig.data[0].x) < smoker_count["No"] assert len(fig.data[1].x) < smoker_count["Yes"] def test_density_scatter_plotly_facet_custom_color() -> None: fig = density_scatter_plotly( - df=df_tips, + df=DF_TIPS, x="total_bill", y="tip", facet_col="smoker", @@ -260,7 +260,7 @@ def test_density_scatter_plotly_facet_density_methods( density: Literal["kde", "empirical"], ) -> None: fig = density_scatter_plotly( - df=df_tips, x="total_bill", y="tip", facet_col="smoker", density=density + df=DF_TIPS, x="total_bill", y="tip", facet_col="smoker", density=density ) assert isinstance(fig, go.Figure) @@ -269,7 +269,7 @@ def test_density_scatter_plotly_facet_density_methods( def test_density_scatter_plotly_facet_size() -> None: fig = density_scatter_plotly( - df=df_tips, x="total_bill", y="tip", size="size", facet_col="smoker" + df=DF_TIPS, x="total_bill", y="tip", size="size", facet_col="smoker" ) assert "marker.size" in fig.data[0] @@ -277,14 +277,14 @@ def test_density_scatter_plotly_facet_size() -> None: def test_density_scatter_plotly_facet_multiple_categories() -> None: - fig = density_scatter_plotly(df=df_tips, x="total_bill", y="tip", facet_col="day") + fig = density_scatter_plotly(df=DF_TIPS, x="total_bill", y="tip", facet_col="day") - assert len(fig.data) == df_tips["day"].nunique() + assert len(fig.data) == DF_TIPS["day"].nunique() def test_density_scatter_plotly_facet_identity_line() -> None: fig = density_scatter_plotly( - df=df_tips, x="total_bill", y="tip", facet_col="smoker", identity_line=True + df=DF_TIPS, x="total_bill", y="tip", facet_col="smoker", identity_line=True ) assert len(fig.layout.shapes) == 2 # Two identity lines, one for each facet @@ -292,7 +292,7 @@ def test_density_scatter_plotly_facet_identity_line() -> None: def test_density_scatter_plotly_facet_hover_template() -> None: fig = density_scatter_plotly( - df=df_tips, x="total_bill", y="tip", facet_col="smoker" + df=DF_TIPS, x="total_bill", y="tip", facet_col="smoker" ) for trace in fig.data: diff --git a/tests/test_structure_viz.py b/tests/test_structure_viz.py index 27798b24..cd527c02 100644 --- a/tests/test_structure_viz.py +++ b/tests/test_structure_viz.py @@ -18,9 +18,9 @@ if TYPE_CHECKING: from collections.abc import Sequence -coords = [[0, 0, 0], [0.5, 0.5, 0.5]] -disordered_struct = Structure( - lattice := np.eye(3) * 5, species=[{"Fe": 0.75, "C": 0.25}, "O"], coords=coords +COORDS = [[0, 0, 0], [0.5, 0.5, 0.5]] +DISORDERED_STRUCT = Structure( + lattice := np.eye(3) * 5, species=[{"Fe": 0.75, "C": 0.25}, "O"], coords=COORDS ) @@ -38,7 +38,7 @@ def test_structure_2d( standardize_struct: bool | None, ) -> None: ax = pmv.structure_2d( - disordered_struct, + DISORDERED_STRUCT, atomic_radii=radii, rotation=rotation, show_bonds=show_bonds, @@ -55,7 +55,7 @@ def test_structure_2d( patch_counts = pd.Series( [type(patch).__name__ for patch in ax.patches] ).value_counts() - assert patch_counts["Wedge"] == len(disordered_struct.composition) + assert patch_counts["Wedge"] == len(DISORDERED_STRUCT.composition) min_expected_n_patches = 182 assert patch_counts["PathPatch"] > min_expected_n_patches @@ -63,7 +63,7 @@ def test_structure_2d( @pytest.mark.parametrize("axis", [True, False, "on", "off", "square", "equal"]) def test_structure_2d_axis(axis: str | bool) -> None: - ax = pmv.structure_2d(disordered_struct, axis=axis) + ax = pmv.structure_2d(DISORDERED_STRUCT, axis=axis) assert isinstance(ax, plt.Axes) assert ax.axes.axison == (axis not in (False, "off")) @@ -75,7 +75,7 @@ def test_structure_2d_axis(axis: str | bool) -> None: def test_structure_2d_site_labels( site_labels: Literal[False, "symbol", "species"] | dict[str, str] | Sequence[str], ) -> None: - ax = pmv.structure_2d(disordered_struct, site_labels=site_labels) + ax = pmv.structure_2d(DISORDERED_STRUCT, site_labels=site_labels) assert isinstance(ax, plt.Axes) if site_labels is False: assert not ax.axes.texts @@ -86,8 +86,8 @@ def test_structure_2d_site_labels( def test_structure_2d_warns() -> None: # for sites with negative fractional coordinates - orig_coords = disordered_struct[0].frac_coords.copy() - disordered_struct[0].frac_coords = [-0.1, 0.1, 0.1] + orig_coords = DISORDERED_STRUCT[0].frac_coords.copy() + DISORDERED_STRUCT[0].frac_coords = [-0.1, 0.1, 0.1] standardize_struct = False try: with pytest.warns( @@ -97,24 +97,24 @@ def test_structure_2d_warns() -> None: f"{standardize_struct=}, you may want to set standardize_struct=True" ), ): - pmv.structure_2d(disordered_struct, standardize_struct=standardize_struct) + pmv.structure_2d(DISORDERED_STRUCT, standardize_struct=standardize_struct) finally: - disordered_struct[0].frac_coords = orig_coords + DISORDERED_STRUCT[0].frac_coords = orig_coords # warns when passing subplot_kwargs for a single structure with pytest.warns( UserWarning, match="subplot_kwargs are ignored when plotting a single structure" ): - pmv.structure_2d(disordered_struct, subplot_kwargs={"facecolor": "red"}) + pmv.structure_2d(DISORDERED_STRUCT, subplot_kwargs={"facecolor": "red"}) -struct1 = Structure(lattice, ["Fe", "O"], coords=coords) +struct1 = Structure(lattice, ["Fe", "O"], coords=COORDS) struct1.properties = {"id": "struct1"} -struct2 = Structure(lattice, ["Co", "O"], coords=coords) +struct2 = Structure(lattice, ["Co", "O"], coords=COORDS) struct2.properties = {Key.mat_id: "struct2"} -struct3 = Structure(lattice, ["Ni", "O"], coords=coords) +struct3 = Structure(lattice, ["Ni", "O"], coords=COORDS) struct3.properties = {"ID": "struct3", "name": "nickel oxide"} # extra properties -struct4 = Structure(lattice, ["Cu", "O"], coords=coords) +struct4 = Structure(lattice, ["Cu", "O"], coords=COORDS) def test_structure_2d_multiple() -> None: @@ -165,7 +165,7 @@ def subplot_title(struct: Structure, key: str | int) -> str: def test_structure_2d_color_warning() -> None: # Copernicium is not in the default color scheme elem_symbol = "Cn" - struct = Structure(np.eye(3) * 5, [elem_symbol] * 2, coords=coords) + struct = Structure(np.eye(3) * 5, [elem_symbol] * 2, coords=COORDS) fallback_color = "gray" for elem_colors in ElemColorScheme: @@ -186,7 +186,7 @@ def test_structure_2d_color_warning() -> None: # create custom color scheme missing an element custom_colors = {"Fe": "red"} - struct = Structure(np.eye(3) * 5, ["Fe", "O"], coords=coords) + struct = Structure(np.eye(3) * 5, ["Fe", "O"], coords=COORDS) with pytest.warns( UserWarning, @@ -300,13 +300,13 @@ def test_structure_2d_color_schemes() -> None: ], ) def test_structure_2d_plotly(kwargs: dict[str, Any]) -> None: - fig = pmv.structure_2d_plotly(disordered_struct, **kwargs) + fig = pmv.structure_2d_plotly(DISORDERED_STRUCT, **kwargs) assert isinstance(fig, go.Figure) # Check if the figure has the correct number of traces expected_traces = 0 if show_sites := kwargs.get("show_sites"): - expected_traces += len(disordered_struct) + expected_traces += len(DISORDERED_STRUCT) if show_unit_cell := kwargs.get("show_unit_cell"): expected_traces += 12 # 12 edges in a cube assert len(fig.data) == expected_traces @@ -343,17 +343,17 @@ def test_structure_2d_plotly(kwargs: dict[str, Any]) -> None: # elif isinstance(kwargs["site_labels"], list): # assert all(label in site_trace.text for label in kwargs["site_labels"]) elif site_labels in ("symbol", "species"): - assert len(site_trace.text) == len(disordered_struct) + assert len(site_trace.text) == len(DISORDERED_STRUCT) def test_structure_2d_plotly_multiple() -> None: - struct1 = Structure(lattice, ["Fe", "O"], coords=coords) + struct1 = Structure(lattice, ["Fe", "O"], coords=COORDS) struct1.properties = {"id": "struct1"} - struct2 = Structure(lattice, ["Co", "O"], coords=coords) + struct2 = Structure(lattice, ["Co", "O"], coords=COORDS) struct2.properties = {Key.mat_id: "struct2"} - struct3 = Structure(lattice, ["Ni", "O"], coords=coords) + struct3 = Structure(lattice, ["Ni", "O"], coords=COORDS) struct3.properties = {"ID": "struct3", "name": "nickel oxide"} - struct4 = Structure(lattice, ["Cu", "O"], coords=coords) + struct4 = Structure(lattice, ["Cu", "O"], coords=COORDS) # Test dict[str, Structure] struct_dict = { @@ -365,7 +365,7 @@ def test_structure_2d_plotly_multiple() -> None: fig = pmv.structure_2d_plotly(struct_dict, n_cols=3) assert isinstance(fig, go.Figure) assert len(fig.data) == 4 * ( - len(coords) + 12 + len(COORDS) + 12 ) # 4 structures, 2 sites each, 12 unit cell edges assert len(fig.layout.annotations) == 4 @@ -373,13 +373,13 @@ def test_structure_2d_plotly_multiple() -> None: struct_series = pd.Series(struct_dict) fig = pmv.structure_2d_plotly(struct_series) assert isinstance(fig, go.Figure) - assert len(fig.data) == 4 * (len(coords) + 12) + assert len(fig.data) == 4 * (len(COORDS) + 12) assert len(fig.layout.annotations) == 4 # Test list[Structure] fig = pmv.structure_2d_plotly(list(struct_dict.values()), n_cols=2) assert isinstance(fig, go.Figure) - assert len(fig.data) == 4 * (len(coords) + 12) + assert len(fig.data) == 4 * (len(COORDS) + 12) assert len(fig.layout.annotations) == 4 # Test subplot_title @@ -388,7 +388,7 @@ def subplot_title(struct: Structure, key: str | int) -> str: fig = pmv.structure_2d_plotly(struct_series, subplot_title=subplot_title) assert isinstance(fig, go.Figure) - assert len(fig.data) == 4 * (len(coords) + 12) + assert len(fig.data) == 4 * (len(COORDS) + 12) assert len(fig.layout.annotations) == 4 for idx, (_key, struct) in enumerate(struct_dict.items(), start=1): assert fig.layout.annotations[idx - 1].text == f"{idx} - {struct.formula}" diff --git a/tests/test_uncertainty.py b/tests/test_uncertainty.py index eef58119..9f6c96e3 100644 --- a/tests/test_uncertainty.py +++ b/tests/test_uncertainty.py @@ -16,14 +16,14 @@ from numpy.typing import ArrayLike -y_std_mock = y_true - y_pred +Y_STD_MOCK = y_true - y_pred @pytest.mark.parametrize( "y_std", [ - y_std_mock, - {"y_std_mock": y_std_mock}, + Y_STD_MOCK, + {"y_std_mock": Y_STD_MOCK}, df_regr.columns[0], # single std col df_regr.columns[:2], # multiple std cols ], @@ -39,7 +39,7 @@ def test_error_decay_with_uncert( df, x, y = df_or_arrays # override y_std if col name but no df provided, would be nonsensical input if df is None and isinstance(y_std, str | pd.Index): - y_std = y_std_mock + y_std = Y_STD_MOCK ax = error_decay_with_uncert( x, y, y_std, df=df, n_rand=n_rand, percentiles=percentiles ) diff --git a/tests/test_xrd.py b/tests/test_xrd.py index bfdf12ff..8fef61d9 100644 --- a/tests/test_xrd.py +++ b/tests/test_xrd.py @@ -15,7 +15,7 @@ if TYPE_CHECKING: from typing import Any -mock_diffraction_pattern = DiffractionPattern( +MOCK_DIFFRACTION_PATTERN = DiffractionPattern( x=[10, 20, 30, 40, 50], y=[100, 50, 75, 25, 60], hkls=[ @@ -28,19 +28,19 @@ d_hkls=[2.5, 2.0, 1.8, 1.5, 1.3], ) -bi2_zr2_o7_struct = Structure.from_file( +BI2_ZR2_O7_STRUCT = Structure.from_file( f"{TEST_FILES}/xrd/Bi2Zr2O7-Fm3m-experimental-sqs.cif" ) -bi2_zr2_o7_xrd = XRDCalculator().get_pattern(bi2_zr2_o7_struct) +BI2_ZR2_O7_XRD = XRDCalculator().get_pattern(BI2_ZR2_O7_STRUCT) @pytest.mark.parametrize( ("input_data", "expected_traces"), [ - (mock_diffraction_pattern, 1), - (bi2_zr2_o7_xrd, 1), - (bi2_zr2_o7_struct, 1), - ({"Structure": bi2_zr2_o7_struct, "Pattern": mock_diffraction_pattern}, 2), + (MOCK_DIFFRACTION_PATTERN, 1), + (BI2_ZR2_O7_XRD, 1), + (BI2_ZR2_O7_STRUCT, 1), + ({"Structure": BI2_ZR2_O7_STRUCT, "Pattern": MOCK_DIFFRACTION_PATTERN}, 2), ], ) def test_xrd_pattern_input_types(input_data: Any, expected_traces: int) -> None: @@ -52,7 +52,7 @@ def test_xrd_pattern_input_types(input_data: Any, expected_traces: int) -> None: @pytest.mark.parametrize("peak_width", [0.3, 0.5, 0.8]) def test_xrd_pattern_peak_width(peak_width: float) -> None: - fig = pmv.xrd_pattern(mock_diffraction_pattern, peak_width=peak_width) + fig = pmv.xrd_pattern(MOCK_DIFFRACTION_PATTERN, peak_width=peak_width) assert fig.data[0].width == peak_width @@ -65,21 +65,21 @@ def test_xrd_pattern_annotate_peaks(annotate_peaks: float) -> None: f"{annotate_peaks=} should be a positive int or a float in (0, 1)" ) with pytest.raises(ValueError, match=err_msg): - pmv.xrd_pattern(mock_diffraction_pattern, annotate_peaks=annotate_peaks) + pmv.xrd_pattern(MOCK_DIFFRACTION_PATTERN, annotate_peaks=annotate_peaks) else: - fig = pmv.xrd_pattern(mock_diffraction_pattern, annotate_peaks=annotate_peaks) + fig = pmv.xrd_pattern(MOCK_DIFFRACTION_PATTERN, annotate_peaks=annotate_peaks) annotations = fig.layout.annotations if isinstance(annotate_peaks, int): assert len(annotations) == min( - annotate_peaks, len(mock_diffraction_pattern.x) + annotate_peaks, len(MOCK_DIFFRACTION_PATTERN.x) ) else: assert len(annotations) > 0 # At least some peaks should be annotated def test_xrd_pattern_hover_data() -> None: - fig = pmv.xrd_pattern(mock_diffraction_pattern) - assert len(fig.data[0].hovertext) == len(mock_diffraction_pattern.x) + fig = pmv.xrd_pattern(MOCK_DIFFRACTION_PATTERN) + assert len(fig.data[0].hovertext) == len(MOCK_DIFFRACTION_PATTERN.x) assert all( all(key in text for key in ["2θ", "Intensity", "hkl", "d"]) for text in fig.data[0].hovertext @@ -87,12 +87,12 @@ def test_xrd_pattern_hover_data() -> None: def test_xrd_pattern_layout_and_range() -> None: - fig = pmv.xrd_pattern(mock_diffraction_pattern) + fig = pmv.xrd_pattern(MOCK_DIFFRACTION_PATTERN) assert fig.layout.xaxis.title.text == "2θ (degrees)" assert fig.layout.yaxis.title.text == "Intensity (a.u.)" assert fig.layout.hovermode == "x" assert fig.layout.xaxis.range[0] == 0 - assert fig.layout.xaxis.range[1] == max(mock_diffraction_pattern.x) + 5 + assert fig.layout.xaxis.range[1] == max(MOCK_DIFFRACTION_PATTERN.x) + 5 assert fig.layout.yaxis.range == (0, 105) @@ -110,7 +110,7 @@ def test_xrd_pattern_annotation_format( hkl_format: pmv.xrd.HklFormat, expected_format: str | None, show_angles: bool ) -> None: fig = pmv.xrd_pattern( - mock_diffraction_pattern, hkl_format=hkl_format, show_angles=show_angles + MOCK_DIFFRACTION_PATTERN, hkl_format=hkl_format, show_angles=show_angles ) if hkl_format is pmv.xrd.HklNone and not show_angles: assert len(fig.layout.annotations) == 0 @@ -137,8 +137,8 @@ def test_xrd_pattern_empty_input() -> None: def test_xrd_pattern_intensity_normalization() -> None: - original_max = max(mock_diffraction_pattern.y) - fig = pmv.xrd_pattern(mock_diffraction_pattern) + original_max = max(MOCK_DIFFRACTION_PATTERN.y) + fig = pmv.xrd_pattern(MOCK_DIFFRACTION_PATTERN) normalized_max = max(fig.data[0].y) assert normalized_max == 100 assert normalized_max / original_max == pytest.approx(100 / original_max) @@ -146,9 +146,9 @@ def test_xrd_pattern_intensity_normalization() -> None: @pytest.mark.parametrize("wavelength", [1.54184, 0.7093]) def test_xrd_pattern_wavelength(wavelength: float) -> None: - fig = pmv.xrd_pattern(bi2_zr2_o7_struct, wavelength=wavelength) + fig = pmv.xrd_pattern(BI2_ZR2_O7_STRUCT, wavelength=wavelength) first_peak_position = fig.data[0].x[0] - reference_fig = pmv.xrd_pattern(bi2_zr2_o7_struct, wavelength=1.54184) + reference_fig = pmv.xrd_pattern(BI2_ZR2_O7_STRUCT, wavelength=1.54184) reference_first_peak = reference_fig.data[0].x[0] if wavelength != 1.54184: assert first_peak_position != reference_first_peak @@ -158,8 +158,8 @@ def test_xrd_pattern_wavelength(wavelength: float) -> None: def test_xrd_pattern_tooltip_content() -> None: patterns = { - "Pattern 1": mock_diffraction_pattern, - "Pattern 2": mock_diffraction_pattern, + "Pattern 1": MOCK_DIFFRACTION_PATTERN, + "Pattern 2": MOCK_DIFFRACTION_PATTERN, } fig = pmv.xrd_pattern(patterns, show_angles=False, hkl_format=None) @@ -172,8 +172,8 @@ def test_xrd_pattern_tooltip_content() -> None: def test_xrd_pattern_tooltip_label() -> None: patterns = { - "Pattern 1": mock_diffraction_pattern, - "Pattern 2": mock_diffraction_pattern, + "Pattern 1": MOCK_DIFFRACTION_PATTERN, + "Pattern 2": MOCK_DIFFRACTION_PATTERN, } fig = pmv.xrd_pattern(patterns)