Skip to content
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

Clean up var names in unit tests, avoid MP API access in GitHub workflow #207

Merged
merged 17 commits into from
Sep 29, 2024
Merged
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
3 changes: 0 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ jobs:
with:
os: ${{ matrix.os }}
python-version: "3.10"
secrets: inherit

find-scripts:
runs-on: ubuntu-latest
Expand Down Expand Up @@ -55,5 +54,3 @@ jobs:

- name: Run script
run: python ${{ matrix.script }}
env:
MP_API_KEY: ${{ secrets.MP_API_KEY }}
28 changes: 21 additions & 7 deletions examples/make_assets/structure_viz.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# %%
import os
from typing import cast

import matplotlib.pyplot as plt
Expand All @@ -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")

Expand All @@ -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}
Expand Down
14 changes: 7 additions & 7 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
Binary file added tests/files/structures/mp-12712.json.gz
Binary file not shown.
Binary file added tests/files/structures/mp-19017.json.gz
Binary file not shown.
4 changes: 0 additions & 4 deletions tests/test_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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"),
Expand Down
1 change: 0 additions & 1 deletion tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 19 additions & 19 deletions tests/test_scatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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",
Expand All @@ -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)
Expand All @@ -269,30 +269,30 @@ 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]
assert "marker.size" in fig.data[1]


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


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:
Expand Down
Loading