repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
wandb
tests/system_tests/test_functional/test_tensorboard/test_wandb_tb_log.py
.py
"""Tests for wandb.tensorboard.log and wandb.tensorboard.WandbHook.""" import pytest import tensorflow as tf import wandb from tensorboard.compat.proto import summary_pb2 def test_wandb_tf_log(wandb_backend_spy, assets_path): with wandb.init(sync_tensorboard=True) as run: summary_pb = open(assets_path("w...
108
4,459
wandb
tests/system_tests/test_functional/test_tensorboard/test_keras_tb_callback.py
.py
"""Based on examples from https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/TensorBoard Test that the Keras TensorBoard callback works with W&B. """ import keras import numpy as np import tensorflow as tf import wandb from tests.fixtures.wandb_backend_spy import WandbBackendSpy class MyModel(keras.Model)...
89
2,725
wandb
tests/system_tests/test_functional/test_tensorboard/test_torch_tb.py
.py
"""Based on the docs: https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter This test is to check if the tensorboard data is being processed correctly and sent to W&B. """ import numpy as np import pytest import torch import wandb from torch.utils.tensorboard import SummaryWrit...
190
7,225
wandb
tests/system_tests/test_functional/test_tensorboard/test_tf_summary.py
.py
"""Test that the TensorFlow summary API works with W&B. Used https://www.tensorflow.org/api_docs/python/tf/summary as reference.""" import os import numpy as np import pytest import tensorboard.plugins.pr_curve.summary as pr_curve_plugins_summary import tensorboard.summary.v1 as tensorboard_summary_v1 import tensorfl...
285
10,396
wandb
tests/system_tests/test_functional/test_tensorboard/test_tensorboardX.py
.py
"""Tests for tensorboardX integration.""" import torch import wandb from tensorboardX import SummaryWriter def test_add_scalar(wandb_backend_spy): with wandb.init(sync_tensorboard=True) as run: with SummaryWriter() as writer: for i in range(10): writer.add_scalar("loss", torch...
64
2,263
wandb
tests/system_tests/test_functional/test_tensorboard/test_tb_w_sb3.py
.py
"""Test stable_baselines3 integration.""" import gymnasium as gym import wandb from stable_baselines3 import PPO from stable_baselines3.common.monitor import Monitor from stable_baselines3.common.vec_env import DummyVecEnv def test_sb3_tensorboard(wandb_backend_spy): """Integration test for Stable Baselines 3 Te...
35
1,118
wandb
tests/system_tests/test_functional/test_tensorboard/conftest.py
.py
import pytest import wandb @pytest.fixture(autouse=True) def unpatch_tensorboard(): yield # Undo any TensorBoard patching after every test in this directory # to prevent order dependence. wandb.tensorboard.unpatch()
12
235
wandb
tests/system_tests/test_functional/interrupt/pass_if_interrupted.py
.py
"""Starts a W&B run and exits with code 1 if it's not interrupted.""" from __future__ import annotations import sys import time import wandb import wandb.sdk.lib.run_stopping if __name__ == "__main__": # The stop status is delivered via a FileStream response. settings = wandb.Settings(x_file_stream_transmit...
36
1,155
wandb
tests/system_tests/test_functional/interrupt/test_interrupt.py
.py
import pathlib import subprocess import threading import pytest import wandb from tests.fixtures.wandb_backend_spy import WandbBackendSpy @pytest.fixture(autouse=True) def fast_stop_polling_interval(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("wandb.sdk.lib.run_stopping._POLL_INTERVAL", 0.1) ...
51
1,279
wandb
tests/system_tests/test_functional/terminput/test_terminput.py
.py
from __future__ import annotations import os import pathlib import subprocess import time from collections.abc import Sequence import click import pytest # Will skip on Windows. pytest.importorskip("pty") import pty # Import using normal syntax for IDE support. _TESTER_SCRIPT = pathlib.Path(__file__).parent / "ter...
235
7,324
wandb
tests/system_tests/test_functional/terminput/terminput_tester.py
.py
import argparse import fcntl import os import sys import termios from wandb.errors.term import terminput if __name__ == "__main__": # Tell the pseudoterminal to which stdin is attached to control # this process, so that it can implement Ctrl+C and so on. os.setsid() fcntl.ioctl(sys.stdin, termios.TIOC...
35
933
wandb
tests/system_tests/test_functional/metaflow/flow_foreach.py
.py
"""Test Metaflow Flow integration""" import os import pathlib import pandas as pd import wandb from metaflow import FlowSpec, Parameter, step from sklearn.ensemble import ( # noqa: F401 GradientBoostingClassifier, RandomForestClassifier, ) from sklearn.metrics import accuracy_score from sklearn.model_selecti...
82
2,282
wandb
tests/system_tests/test_functional/metaflow/flow_decostep.py
.py
"""Test Metaflow Flow integration""" import os import pathlib import pandas as pd import wandb from metaflow import FlowSpec, Parameter, step from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from wandb.integration.metaf...
60
1,686
wandb
tests/system_tests/test_functional/metaflow/test_metaflow.py
.py
import pathlib import subprocess def test_flow_decoboth(wandb_backend_spy): """Test that the flow_decoboth.py script runs correctly.""" script_path = pathlib.Path(__file__).parent / "flow_decoboth.py" subprocess.check_call(["python", str(script_path), "--no-pylint", "run"]) with wandb_backend_spy.fre...
127
5,095
wandb
tests/system_tests/test_functional/metaflow/flow_pytorch.py
.py
"""Test Metaflow Flow integration""" import os import torch import torch.nn as nn import torch.nn.functional as F # noqa: N812 import torch.optim as optim import wandb from metaflow import FlowSpec, Parameter, step from torch.optim.lr_scheduler import StepLR from torchvision import datasets, transforms from wandb.in...
147
4,604
wandb
tests/system_tests/test_functional/metaflow/flow_decoboth.py
.py
"""Test Metaflow Flow integration""" import os import pathlib import pandas as pd import wandb from metaflow import FlowSpec, Parameter, step from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from wandb.integration.metaf...
59
1,709
wandb
tests/system_tests/test_functional/metaflow/flow_decoclass.py
.py
"""Test Metaflow Flow integration""" import os import pathlib import pandas as pd import wandb from metaflow import FlowSpec, Parameter, step from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from wandb.integration.metaf...
58
1,665
wandb
tests/system_tests/test_functional/catboost/regression.py
.py
import wandb from catboost import CatBoostClassifier, Pool, datasets from wandb.integration.catboost import WandbCallback, log_summary train_df, _ = datasets.msrank_10k() X, Y = train_df[train_df.columns[1:]], train_df[train_df.columns[0]] pool = Pool( data=X[:1000], label=Y[:1000], feature_names=list(X.co...
19
575
wandb
tests/system_tests/test_functional/catboost/test_catboost.py
.py
import pathlib def test_regression(wandb_backend_spy, execute_script): script_path = pathlib.Path(__file__).parent / "regression.py" execute_script(script_path) with wandb_backend_spy.freeze() as snapshot: run_ids = snapshot.run_ids() assert len(run_ids) == 1 run_id = run_ids.pop(...
28
1,076
wandb
tests/system_tests/test_functional/test_util/util_import_lazy.py
.py
import wandb.util as util util.get_module("PIL.Image", lazy=True) # ruff: noqa import PIL.Image assert hasattr(PIL.Image, "Image")
9
134
wandb
tests/system_tests/test_functional/test_util/test_util.py
.py
import pathlib import subprocess def test_util_import_adds_attribute_to_parent_module(): script = pathlib.Path(__file__).parent / "util_import_lazy.py" subprocess.check_call(["python", str(script)])
8
209
wandb
tests/system_tests/test_functional/xgboost/regression.py
.py
import pathlib import numpy as np import pandas as pd import wandb import xgboost as xgb from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from wandb.integration.xgboost import WandbCallback # Generated using: # # from sklearn.datasets import fetch_california_housin...
50
1,306
wandb
tests/system_tests/test_functional/xgboost/classification.py
.py
import pathlib import pandas as pd import wandb from sklearn.model_selection import train_test_split from wandb.integration.xgboost import WandbCallback from xgboost import XGBClassifier # Generated using: # # from sklearn.datasets import load_wine # # load_wine(as_frame=True).frame.sample(n=100).to_csv(..., inde...
38
951
wandb
tests/system_tests/test_functional/xgboost/test_xgboost.py
.py
import pathlib def test_classification(wandb_backend_spy, execute_script): script_path = pathlib.Path(__file__).parent / "classification.py" execute_script(script_path) with wandb_backend_spy.freeze() as snapshot: run_ids = snapshot.run_ids() assert len(run_ids) == 1 run_id = run_...
62
2,597
wandb
tests/system_tests/test_functional/dspy/dspy_callback_unexpected.py
.py
import dspy import wandb class MinimalProgram(dspy.Module): def __init__(self) -> None: super().__init__() self.predict = dspy.Predict("question: str -> answer: str") def main() -> None: from wandb.integration.dspy import WandbDSPyCallback with wandb.init(project="dspy-system-test-unexp...
39
997
wandb
tests/system_tests/test_functional/dspy/dspy_callback.py
.py
import dspy import wandb from dspy.evaluate.evaluate import EvaluationResult # type: ignore class MinimalProgram(dspy.Module): """Minimal DSPy module exposing a `Predict` param for signature extraction. Examples: >>> mod = MinimalProgram() """ def __init__(self) -> None: super().__i...
86
2,564
wandb
tests/system_tests/test_functional/dspy/dspy_callback_exception.py
.py
import dspy import wandb from dspy.evaluate.evaluate import EvaluationResult # type: ignore class MinimalProgram(dspy.Module): def __init__(self) -> None: super().__init__() self.predict = dspy.Predict("question: str -> answer: str") def _build_results_stub(): ex1 = dspy.Example(question="W...
44
1,230
wandb
tests/system_tests/test_functional/dspy/dspy_callback_no_program.py
.py
import dspy import wandb from dspy.evaluate.evaluate import EvaluationResult # type: ignore class MinimalProgram(dspy.Module): def __init__(self) -> None: super().__init__() self.predict = dspy.Predict("question: str -> answer: str") def main() -> None: from wandb.integration.dspy import Wa...
36
1,137
wandb
tests/system_tests/test_functional/dspy/test_dspy.py
.py
from __future__ import annotations import importlib from collections.abc import Callable from typing import Any import pytest @pytest.fixture def run_and_snapshot(wandb_backend_spy): """Factory fixture to run a dspy example module and collect W&B snapshot. Args: wandb_backend_spy: Spy fixture for W...
276
9,406
wandb
tests/system_tests/test_functional/dspy/dspy_callback_completions.py
.py
import dspy import wandb from dspy.evaluate.evaluate import EvaluationResult # type: ignore class MinimalProgram(dspy.Module): def __init__(self) -> None: super().__init__() self.predict = dspy.Predict("question: str -> answer: str") class DummyCompletions: """Minimal stand-in for dspy.Comp...
54
1,559
wandb
tests/system_tests/test_functional/dspy/dspy_callback_log_results_false.py
.py
import dspy import wandb from dspy.evaluate.evaluate import EvaluationResult # type: ignore class MinimalProgram(dspy.Module): def __init__(self) -> None: super().__init__() self.predict = dspy.Predict("question: str -> answer: str") def _build_results_stub(): ex1 = dspy.Example(question="W...
42
1,159
wandb
tests/system_tests/test_functional/dspy/dspy_callback_multiple_steps.py
.py
import dspy import wandb from dspy.evaluate.evaluate import EvaluationResult # type: ignore class MinimalProgram(dspy.Module): def __init__(self) -> None: super().__init__() self.predict = dspy.Predict("question: str -> answer: str") def _results(score_value: float): ex = dspy.Example(quest...
44
1,262
wandb
tests/system_tests/test_functional/keras/keras_eval_tables_builder.py
.py
import numpy as np import tensorflow as tf import wandb from wandb.integration.keras import WandbEvalCallback tf.keras.utils.set_random_seed(1234) run = wandb.init(project="keras") x = np.random.randint(255, size=(100, 28, 28, 1)) y = np.random.randint(10, size=(100,)) dataset = (x, y) def get_model(): model =...
76
2,059
wandb
tests/system_tests/test_functional/keras/keras_model_checkpoint.py
.py
import numpy as np import tensorflow as tf import wandb from wandb.integration.keras import WandbModelCheckpoint run = wandb.init(project="keras") x = np.random.randint(255, size=(100, 28, 28, 1)) y = np.random.randint(10, size=(100,)) dataset = (x, y) def get_model(): m = tf.keras.Sequential() m.add(tf.ke...
47
991
wandb
tests/system_tests/test_functional/keras/keras_metrics_logger.py
.py
import numpy as np import tensorflow as tf import wandb from wandb.integration.keras import WandbMetricsLogger tf.keras.utils.set_random_seed(1234) run = wandb.init(project="keras") x = np.random.randint(255, size=(100, 28, 28, 1)) y = np.random.randint(10, size=(100,)) dataset = (x, y) def get_model(): model...
39
843
wandb
tests/system_tests/test_functional/keras/keras_metrics_logger_epochwise.py
.py
import numpy as np import tensorflow as tf import wandb from wandb.integration.keras import WandbMetricsLogger tf.keras.utils.set_random_seed(1234) run = wandb.init(project="keras") x = np.random.randint(255, size=(100, 28, 28, 1)) y = np.random.randint(10, size=(100,)) dataset = (x, y) def get_model(): model...
48
1,035
wandb
tests/system_tests/test_functional/keras/test_keras.py
.py
import pathlib import subprocess def test_eval_tables_builder(wandb_backend_spy): script_path = pathlib.Path(__file__).parent / "keras_eval_tables_builder.py" subprocess.check_call(["python", str(script_path)]) with wandb_backend_spy.freeze() as snapshot: run_ids = snapshot.run_ids() asse...
69
2,396
wandb
tests/system_tests/test_functional/sync/test_sync.py
.py
from __future__ import annotations import concurrent.futures import queue import subprocess import time import wandb from tests.fixtures.wandb_backend_spy import WandbBackendSpy _TIMEOUT_SLOW = 5 # Timeout for operations that may be slow. _TIMEOUT_NORMAL = 1 # Timeout for operations that are probably not too slow....
80
2,681
wandb
tests/system_tests/test_functional/jax/test_jax.py
.py
import jax.numpy as jnp import wandb def test_log_bfloat16(wandb_backend_spy): run = wandb.init() m1 = jnp.array(1.0, dtype=jnp.float32) m2 = jnp.array(2.0, dtype=jnp.bfloat16) m3 = jnp.array([3.0, 4.0], dtype=jnp.bfloat16) run.log(dict(m1=m1, m2=m2, m3=m3)) run.finish() with wandb_backen...
22
609
wandb
tests/system_tests/test_functional/lightning/strategy_ddp_spawn.py
.py
from base import BoringModel, RandomDataset # type: ignore from lightning import Trainer from lightning.pytorch.loggers import WandbLogger from torch.utils.data import DataLoader def main(): # Set up data num_samples = 1000 train = DataLoader(RandomDataset(32, num_samples), batch_size=32) val = DataL...
38
1,004
wandb
tests/system_tests/test_functional/lightning/test_lightning.py
.py
import pathlib def test_strategy_ddp_spawn(wandb_backend_spy, execute_script): script_path = pathlib.Path(__file__).parent / "strategy_ddp_spawn.py" execute_script(script_path) with wandb_backend_spy.freeze() as snapshot: run_ids = snapshot.run_ids() assert len(run_ids) == 1 run_i...
41
1,530
wandb
tests/system_tests/test_functional/lightning/base.py
.py
import torch from lightning import LightningModule from torch.utils.data import Dataset class RandomDataset(Dataset): def __init__(self, size, num_samples): self.len = num_samples self.data = torch.randn(num_samples, size) def __getitem__(self, index): return self.data[index] def...
69
2,209
wandb
tests/system_tests/test_functional/lightning/strategy_ddp.py
.py
import lightning as pl from base import BoringModel, RandomDataset # type: ignore from lightning.pytorch.loggers import WandbLogger from torch.utils.data import DataLoader def main(): # Set up data num_samples = 1000 train = RandomDataset(32, num_samples) train = DataLoader(train, batch_size=32) ...
42
1,063
wandb
tests/system_tests/test_functional/wb_logging/last_resort.py
.py
import logging if __name__ == "__main__": logger = logging.getLogger("wandb") # logging.lastResort by default outputs to stderr. Check that this is true. logger.warning("lastResort (before configuring)") # Import wandb to trigger wb_logging.configure_wandb_logger(). import wandb # noqa: F401 ...
20
754
wandb
tests/system_tests/test_functional/wb_logging/test_wb_logging_last_resort.py
.py
import pathlib import subprocess def test_wb_logging_last_resort(): script = pathlib.Path(__file__).parent / "last_resort.py" output = subprocess.check_output( # Prevent warnings from 3rd party libraries from polluting the output. ["python", "-W", "ignore", str(script)], stderr=subpro...
18
473
wandb
tests/system_tests/test_functional/console_capture/removes_callback_on_error.py
.py
"""Exits with code 0 if callbacks are removed after raising an exception.""" import sys from wandb.sdk.lib import console_capture num_calls = 0 def count_and_interrupt(*unused) -> None: global num_calls num_calls += 1 raise KeyboardInterrupt if __name__ == "__main__": console_capture.capture_std...
39
961
wandb
tests/system_tests/test_functional/console_capture/uncapturing.py
.py
"""Exits with code 0 if callbacks can be unregistered.""" from __future__ import annotations import io import sys from wandb.sdk.lib import console_capture received_by_hooks = io.StringIO() def _stdout_hook1(data: str | bytes, written: int, /): received_by_hooks.write("[hook1]" + str(data[:written])) def _s...
42
1,088
wandb
tests/system_tests/test_functional/console_capture/test_console_capture.py
.py
import pathlib import subprocess def test_deadlocks(): script = pathlib.Path(__file__).parent / "deadlocks.py" subprocess.check_call(["python", str(script)], timeout=5) def test_infinite_loop(): script = pathlib.Path(__file__).parent / "infinite_loop.py" subprocess.check_call(["python", str(script)]...
44
1,289
wandb
tests/system_tests/test_functional/console_capture/infinite_loop.py
.py
"""Fails if tasks started by console callbacks invoke more callbacks.""" from __future__ import annotations import asyncio import sys from wandb.sdk.lib import asyncio_manager, console_capture def _info(msg: str) -> None: sys.stderr.write(msg + "\n") class _Tester: def __init__(self) -> None: sel...
69
1,991
wandb
tests/system_tests/test_functional/console_capture/patch_stdout_and_stderr.py
.py
"""Exits with code 0 if stdout and stderr callbacks are triggered. On success, prints "I AM STDOUT" to stdout and "I AM STDERR" to stderr. On error, prints additional text to stderr. """ import sys from wandb.sdk.lib import console_capture _got_stdout = False _got_stderr = False def _on_stdout(s, n): global _...
41
837
wandb
tests/system_tests/test_functional/console_capture/patching_exception.py
.py
"""Exits with code 0 if an exception patching stdout is rethrown.""" import io import sys from typing import TextIO class _TestError(Exception): pass class MyStdout(io.TextIOBase): def __init__(self, delegate: TextIO) -> None: self._delegate = delegate def __setattr__(self, name, value): ...
58
1,708
wandb
tests/system_tests/test_functional/console_capture/deadlocks.py
.py
"""Exits with code 0 if no deadlock occurs, and hangs otherwise.""" from __future__ import annotations import concurrent.futures import sys from wandb.sdk.lib import console_capture def _info(msg: str) -> None: sys.stderr.write(msg + "\n") def _main() -> None: reset = console_capture.capture_stdout(_chec...
41
1,106
wandb
tests/system_tests/test_functional/asyncio_compat_run/pass_if_cancelled.py
.py
import asyncio import sys import threading import time from wandb.sdk.lib import asyncio_compat _got_cancelled = threading.Event() async def pass_if_cancelled() -> None: global _got_cancelled try: print(f"Ready at {time.monotonic()}", file=sys.stderr) print("TEST READY", flush=True) ...
58
1,757
wandb
tests/system_tests/test_functional/asyncio_compat_run/test_asyncio_compat_run.py
.py
import pathlib import signal import subprocess def test_asyncio_compat_run_stops_on_keyboard_interrupt(): script = pathlib.Path(__file__).parent / "pass_if_cancelled.py" proc = subprocess.Popen( ["python", str(script)], stdout=subprocess.PIPE, ) # Wait for process to enter the asyncio...
18
463
wandb
tests/system_tests/test_artifacts/test_wandb_run_artifacts.py
.py
from __future__ import annotations import os from contextlib import nullcontext from pathlib import Path from typing import TYPE_CHECKING import wandb from pytest import FixtureRequest, fixture, mark, raises from pytest_mock import MockerFixture from wandb import Artifact, env from wandb.errors import CommError from ...
394
12,753
wandb
tests/system_tests/test_artifacts/test_misc.py
.py
from __future__ import annotations import re import time import uuid from operator import attrgetter from pathlib import Path import numpy as np import wandb from pytest import fail, raises from wandb import Api from wandb.apis import public def assert_eq_runs( run_a: wandb.Run | public.Run, run_b: wandb.Run | ...
155
5,399
wandb
tests/system_tests/test_artifacts/test_model_workflows.py
.py
from __future__ import annotations from pathlib import Path import wandb from pytest import raises from wandb import env class FakeArtifact: def wait(self): pass def is_draft(self): return False def test_offline_link_artifact(user): with wandb.init(mode="offline") as run: with...
94
2,962
wandb
tests/system_tests/test_artifacts/test_artifact_saver.py
.py
from __future__ import annotations from unittest.mock import Mock from pytest import mark, raises from wandb.sdk.artifacts.artifact_saver import ArtifactSaver from wandb.sdk.internal import file_pusher, file_stream, internal_api def mock_upload_urls( project: str, files, run=None, entity=None, d...
132
3,829
wandb
tests/system_tests/test_artifacts/test_artifact_public_api.py
.py
from __future__ import annotations import os import platform import random import string from collections.abc import Callable from contextlib import nullcontext from itertools import islice from pathlib import Path import wandb from pytest import MonkeyPatch, fixture, mark, raises, skip from wandb import Api from wan...
790
25,913
wandb
tests/system_tests/test_artifacts/test_wandb_artifacts_api.py
.py
from __future__ import annotations import json import os import re import time from pathlib import Path import responses import wandb from pytest import mark, raises from wandb import Api from wandb.errors import CommError from wandb.sdk.artifacts.artifact import Artifact def _fetch_artifact_with_tags( api: Api...
632
21,320
wandb
tests/system_tests/test_artifacts/test_wandb_artifacts.py
.py
from __future__ import annotations import filecmp import os import shutil from collections.abc import Callable, Generator, Mapping from concurrent.futures import ThreadPoolExecutor from contextlib import nullcontext from datetime import datetime, timedelta, timezone from pathlib import Path, PurePosixPath, PureWindows...
1,440
48,706
wandb
tests/system_tests/test_artifacts/test_gqlutils.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Any, Protocol from pytest import fixture, mark, raises from wandb.proto import wandb_internal_pb2 as pb from wandb.sdk.artifacts._gqlutils import resolve_org_entity_name, server_supports if TYPE_CHECKING: from wandb import Api from tests.f...
336
9,404
wandb
tests/system_tests/test_artifacts/test_link_artifacts.py
.py
from __future__ import annotations import wandb from pytest import raises def test_get_artifact_collection_from_linked_artifact(linked_artifact): collection = linked_artifact.collection assert linked_artifact.entity == collection.entity assert linked_artifact.project == collection.project assert link...
178
6,734
wandb
tests/system_tests/test_artifacts/test_wandb_artifacts_full.py
.py
from __future__ import annotations import os import platform import re import shutil import time from datetime import datetime, timedelta, timezone from pathlib import Path import numpy as np import responses import wandb from pytest import MonkeyPatch, mark, raises from pytest_mock import MockerFixture from wandb im...
911
33,614
wandb
tests/system_tests/test_artifacts/test_misc2.py
.py
from __future__ import annotations from collections.abc import Callable import numpy as np import wandb from pytest import mark, raises from wandb.sdk.artifacts.exceptions import ArtifactNotLoggedError def test_artifact_log_with_network_error(wandb_backend_spy): gql = wandb_backend_spy.gql wandb_backend_spy...
249
8,676
wandb
tests/system_tests/test_artifacts/test_artifact_cli.py
.py
from __future__ import annotations import os import platform from pathlib import Path from pytest import mark from wandb.cli import cli from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache from wandb.sdk.lib.filesystem import mkdir_exists_ok def test_artifact(runner, user): # wandb artifa...
98
3,382
wandb
tests/system_tests/test_artifacts/test_object_references.py
.py
from __future__ import annotations import shutil import time from collections.abc import Callable from contextlib import suppress from pathlib import Path from typing import Literal import boto3 import botocore import google.cloud.storage import numpy as np import wandb from bokeh.plotting import figure from pytest i...
1,107
35,793
wandb
tests/system_tests/test_artifacts/test_data_types.py
.py
from __future__ import annotations import time from collections.abc import Callable from typing import TYPE_CHECKING, TypeAlias import matplotlib import numpy as np import wandb from pytest import MonkeyPatch, fixture, mark, raises from wandb import Api from wandb.data_types import Table, WBValue from wandb.sdk.data_...
570
18,850
wandb
tests/system_tests/test_artifacts/conftest.py
.py
from __future__ import annotations from pathlib import Path import wandb from pytest import MonkeyPatch, fixture from wandb import Api, Artifact, env from wandb.sdk.artifacts.staging import get_staging_dir @fixture def logged_artifact(user: str, example_files, api: Api) -> Artifact: with wandb.init(entity=user,...
55
1,968
wandb
tests/system_tests/test_core/test_wandb_save.py
.py
import wandb def test_uploads_at_end(wandb_backend_spy, tmp_path): file = tmp_path / "my_test_dir" / "my_test_file.txt" file.parent.mkdir() file.write_text("testing testing") with wandb.init() as run: run.save(file, policy="end") with wandb_backend_spy.freeze() as snapshot: asser...
16
418
wandb
tests/system_tests/test_core/test_offline_sync_beta.py
.py
from __future__ import annotations import asyncio import pathlib import re from collections.abc import Callable from typing import cast import looptime import pytest import wandb from click.testing import CliRunner from typing_extensions import Any, TypeVar from wandb.cli import beta_sync, cli from wandb.proto import...
615
19,424
wandb
tests/system_tests/test_core/test_leet.py
.py
import subprocess from wandb.util import get_core_path def test_leet_help_smoke(): """Smoke test: verify leet binary works and shows help.""" core_path = get_core_path() # Run wandb-core leet --help result = subprocess.run( [core_path, "leet", "--help"], capture_output=True, ...
20
447
wandb
tests/system_tests/test_core/test_telemetry_full.py
.py
from unittest import mock import wandb from wandb.proto.wandb_telemetry_pb2 import Feature # TODO: implement the telemetry context resolver def get_features(telemetry) -> set[str]: features = telemetry.get("3", []) return { Feature.DESCRIPTOR.fields_by_number[feature_number].name for feature...
134
4,318
wandb
tests/system_tests/test_core/test_file_upload.py
.py
import platform import pytest import wandb @pytest.mark.parametrize( "x_primary, files", [ ( True, { "wandb-metadata.json", "wandb-summary.json", "output.log", "config.yaml", "requirements.txt", ...
66
1,866
wandb
tests/system_tests/test_core/test_wandb_integration.py
.py
"""Test the full stack by launching a real backend server. You won't get credit for coverage of the backend logic in these tests. See test_sender.py for testing specific backend logic, or wandb_test.py for testing frontend logic. Be sure to use `test_settings` or an isolated directory """ import importlib import os...
178
6,009
wandb
tests/system_tests/test_core/test_git.py
.py
import subprocess import pytest import wandb def run_git(cwd, *args: str) -> str: return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip() def init_git_repo(path) -> None: subprocess.run(["git", "init", path], check=True, stdout=subprocess.DEVNULL) run_git(path, "config", "user.name",...
288
9,625
wandb
tests/system_tests/test_core/test_wandb.py
.py
"""Test the high level sdk methods by mocking out the backend. See wandb_integration_test.py for tests that launch a real backend server. """ import glob import io import os import platform import tempfile import unittest.mock from contextlib import contextmanager from pathlib import Path from unittest import mock i...
575
15,814
wandb
tests/system_tests/test_core/test_tb_watcher.py
.py
from wandb.sdk.internal import tb_watcher class TestIsTfEventsFileCreatedBy: def test_simple(self): assert tb_watcher.is_tfevents_file_created_by( "out.writer.tfevents.193.me.94.5", "me", 193 ) def test_no_tfevents(self): assert ( tb_watcher.is_tfevents_file_cr...
62
1,682
wandb
tests/system_tests/test_core/test_console.py
.py
import logging import os import re import time import pytest import tqdm import wandb from click.testing import CliRunner from wandb.cli import cli from wandb.sdk.lib import runid from tests.fixtures.wandb_backend_spy import WandbBackendSpy def test_console_wrap_raw(wandb_backend_spy): with wandb.init(settings=...
153
5,106
wandb
tests/system_tests/test_core/test_file_stream.py
.py
import numpy as np import pytest import wandb from wandb.proto import wandb_internal_pb2 as pb @pytest.mark.parametrize("status_code", [429, 500]) def test_retries_retryable_codes(status_code, wandb_backend_spy): wandb_backend_spy.stub_filestream( "transient error", status=status_code, n_t...
88
2,589
wandb
tests/system_tests/test_core/test_label_full.py
.py
"""label full tests.""" import inspect import sys import pytest import wandb @pytest.fixture() def doc_inject(user): m = sys.modules.get("__main__") main_doc = getattr(m, "__doc__", None) def fn(new_doc=None, labels=None, init_kwargs=None): init_kwargs = init_kwargs or {} # clean up lea...
237
6,984
wandb
tests/system_tests/test_core/test_mode_disabled_full.py
.py
"""disabled mode test.""" import os from unittest import mock import pytest import wandb def test_disabled_noop(user): """Make sure that all objects are dummy objects in noop case.""" with wandb.init(mode="disabled") as run: run.log(dict(this=2)) def test_disabled_dir(): tmp_dir = "/tmp/dir" ...
129
3,514
wandb
tests/system_tests/test_core/test_wandb_verify.py
.py
import unittest.mock import wandb import wandb.sdk.verify.verify as wandb_verify from wandb.apis import InternalApi def test_check_logged_in(user): internal_api = unittest.mock.MagicMock(spec=InternalApi) internal_api.api_key = None assert not wandb_verify.check_logged_in(internal_api, "localhost:8000") ...
16
439
wandb
tests/system_tests/test_core/test_resume.py
.py
import json from pathlib import Path import numpy as np import pytest import wandb import wandb.errors from wandb.sdk.lib import runid @pytest.mark.parametrize("resume", ("allow", "never")) def test_resume__no_run__success(user, resume): _ = user # Create a fake user for the test. with wandb.init(resume=re...
306
8,891
wandb
tests/system_tests/test_core/test_wandb_init.py
.py
import json import os import re from pathlib import Path from unittest import mock import pytest import wandb from wandb.errors import AuthenticationError, CommError from wandb.sdk.lib import runid from tests.fixtures.wandb_backend_spy import WandbBackendSpy def test_init_timeout__prints_retry_err(wandb_backend_spy...
195
6,035
wandb
tests/system_tests/test_core/test_wandb_clean_full.py
.py
import os import pytest import wandb from click.testing import CliRunner from wandb.cli import cli from wandb.cli.clean import clean @pytest.mark.usefixtures("user") # for syncing and the online run def test_cleans_expected_runs(runner: CliRunner): """An integration test for wandb clean, wandb sync and online l...
30
980
wandb
tests/system_tests/test_core/test_wandb_run.py
.py
import math import os import pickle import sys from pathlib import Path import numpy as np import PIL.Image import pytest import wandb from wandb.errors import UsageError from tests.fixtures.mock_wandb_log import MockWandbLog from tests.fixtures.wandb_backend_spy import WandbBackendSpy def test_log_nan_inf(wandb_ba...
408
12,799
wandb
tests/system_tests/test_core/test_offline_sync.py
.py
import unittest.mock import pytest from wandb.cli import cli from wandb.sdk.lib.runid import generate_id @pytest.mark.flaky def test_sync_with_tensorboard(wandb_backend_spy, runner, copy_asset): run_id = generate_id() with unittest.mock.patch.dict("os.environ", {"WANDB_MODE": "offline"}): tf_event = ...
22
776
wandb
tests/system_tests/test_core/test_cli_full.py
.py
import netrc import os from unittest import mock import pytest import wandb import wandb.errors.term from wandb.cli import cli from wandb.sdk import wandb_setup @pytest.fixture def empty_netrc(monkeypatch): class FakeNet: @property def hosts(self): return {"api.wandb.ai": None} m...
206
7,083
wandb
tests/system_tests/test_core/test_run_messages_full.py
.py
"""Integration tests for the run_messages mechanism.""" import pytest import wandb from tests.fixtures.mock_wandb_log import MockWandbLog @pytest.mark.usefixtures("user") # test requires an online run def test_prints_run_messages(mock_wandb_log: MockWandbLog): # This test may need to be rewritten if the messag...
23
707
wandb
tests/system_tests/test_core/test_data_types_full.py
.py
import json import platform from pathlib import Path from unittest import mock import moviepy.video.io.ImageSequenceClip import numpy as np import PIL.Image import pytest import soundfile as sf import wandb from bokeh.document import Document from bokeh.plotting import figure def create_image(temp_dir) -> Path: ...
248
6,977
wandb
tests/system_tests/test_core/test_torch_full.py
.py
import pytest import wandb import wandb.sdk try: import torch import torch.nn as nn import torch.nn.functional as F # noqa: N812 except ImportError: class nn: # noqa: N801 Module = object def dummy_torch_tensor(size, requires_grad=True): return torch.ones(size, requires_grad=requires_g...
245
7,333
wandb
tests/system_tests/test_core/test_wandb_login.py
.py
import os from unittest import mock import pytest import wandb from wandb.sdk.lib.wbauth import wbnetrc def test_login_valid_key(user): logged_in = wandb.login(verify=True) assert logged_in def test_login_invalid_key_from_environment_raises(user): with mock.patch.dict("os.environ", {"WANDB_API_KEY": "I...
54
1,439
wandb
tests/system_tests/test_core/test_mp_full.py
.py
"""multiproc full tests.""" import importlib import sys import time import pytest import wandb from wandb.errors import UsageError def train(run, add_val): time.sleep(1) run.log(dict(mystep=1, val=2 + add_val)) run.log(dict(mystep=2, val=8 + add_val)) run.log(dict(mystep=3, val=3 + add_val)) run...
57
1,514
wandb
tests/system_tests/test_core/test_resume_auto.py
.py
import json import pathlib import pytest import wandb class AutoResumeTestError(Exception): """Raised in auto-resume tests to leave behind an auto-resume file.""" def test_autoresume_first_run_saves(): with pytest.raises(AutoResumeTestError): with wandb.init(mode="offline", resume="auto") as run: ...
69
2,149
wandb
tests/system_tests/test_core/test_wandb_setup.py
.py
import asyncio import json import os from unittest import mock import pytest import wandb from wandb.sdk import wandb_setup from wandb.sdk.lib import asyncio_manager def test_service_logging_level_debug(): """Test the service logging is debug. Verifies that the service logging level is set to DEBUG when the...
72
2,204
wandb
tests/system_tests/test_core/test_public_api.py
.py
"""Tests for the `wandb.apis.PublicApi` module.""" from __future__ import annotations import json from typing import Any from unittest import mock import pytest import wandb import wandb.apis.public import wandb.util from wandb import Api from wandb.apis._generated import ProjectFragment, UserFragment from wandb.api...
1,489
45,004
wandb
tests/system_tests/test_core/test_save_policies.py
.py
import os import time import pytest import wandb from wandb.filesync.dir_watcher import PolicyLive @pytest.fixture def mocked_live_policy(monkeypatch, user): run = wandb.init() fpath = os.path.join(run.dir, "test_file") with open(fpath, "w") as fp: fp.write("") live_policy = PolicyLive(fpath...
83
2,818
wandb
tests/system_tests/test_core/test_wandb_settings.py
.py
"""settings test.""" import os import platform import subprocess from unittest import mock import pytest import wandb from wandb import env @pytest.mark.skipif( platform.system() == "Windows", reason="backend crashes on Windows in CI" ) def test_sync_dir(user): with wandb.init(settings={"mode": "offline"}) ...
162
4,966
wandb
tests/system_tests/test_core/test_time_resolution.py
.py
import time import wandb def test_log(wandb_backend_spy): """Make sure log is generating history with subsecond resolution.""" before = time.time() with wandb.init() as run: for i in range(10): run.log(dict(k=i)) time.sleep(0.000010) # 10 us after = time.time() w...
32
966