Skip to content
Open
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
1 change: 1 addition & 0 deletions doc/tool_usage_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ This repo is currently migrating all checks from a slower `tox`-based framework,
|`import_all`| Installs the package w/ default dependencies, then attempts to `import *` from the base namespace. Ensures that all imports will resolve after a base install and import. | `azpysdk import_all .` |
|`generate`| Regenerates the code. | `azpysdk generate .` |
|`breaking`| Checks for breaking changes. | `azpysdk breaking .` |
|`devtest`| Tests a package against dependencies installed from a dev index. | `azpysdk devtest .` |

## Common arguments

Expand Down
30 changes: 30 additions & 0 deletions eng/tools/azure-sdk-tools/azpysdk/Check.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,33 @@ def pip_freeze(self, executable: str) -> None:
logger.error(f"Failed to run pip freeze: {e}")
logger.error(e.stdout)
logger.error(e.stderr)

def _build_pytest_args(self, package_dir: str, args: argparse.Namespace) -> List[str]:
"""
Builds the pytest arguments used for the given package directory.

:param package_dir: The package directory to build pytest args for.
:param args: The argparse.Namespace object containing command-line arguments.
:return: A list of pytest arguments.
"""
log_level = os.getenv("PYTEST_LOG_LEVEL", "51")
junit_path = os.path.join(package_dir, f"test-junit-{args.command}.xml")

default_args = [
"-rsfE",
f"--junitxml={junit_path}",
"--verbose",
"--cov-branch",
"--durations=10",
"--ignore=azure",
"--ignore=.tox",
"--ignore-glob=.venv*",
"--ignore=build",
"--ignore=.eggs",
"--ignore=samples",
f"--log-cli-level={log_level}",
]

additional = args.pytest_args if args.pytest_args else []

return [*default_args, *additional, package_dir]
210 changes: 210 additions & 0 deletions eng/tools/azure-sdk-tools/azpysdk/devtest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import argparse
import sys
import os
import glob

from typing import Optional, List

from .Check import Check
from ci_tools.functions import (
install_into_venv,
uninstall_from_venv,
is_error_code_5_allowed,
discover_targeted_packages,
)
from ci_tools.scenario.generation import create_package_and_install
from ci_tools.variables import discover_repo_root, set_envvar_defaults
from ci_tools.logging import logger

REPO_ROOT = discover_repo_root()
common_task_path = os.path.abspath(os.path.join(REPO_ROOT, "scripts", "devops_tasks"))
sys.path.append(common_task_path)

from common_tasks import get_installed_packages

EXCLUDED_PKGS = [
"azure-common",
]

# index URL to devops feed
DEV_INDEX_URL = "https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-python/pypi/simple"

TEST_TOOLS_REQUIREMENTS = os.path.join(REPO_ROOT, "eng/test_tools.txt")


def get_installed_azure_packages(executable: str, pkg_name_to_exclude: str) -> List[str]:
"""
Returns a list of installed Azure SDK packages in the venv, excluding specified packages.

:param executable: Path to the Python executable in the venv.
:param pkg_name_to_exclude: Package name to exclude from the result.
:return: List of installed Azure SDK package names.
"""
venv_root = os.path.dirname(os.path.dirname(executable))
# Find site-packages directory within the venv
if os.name == "nt":
site_packages_pattern = os.path.join(venv_root, "Lib", "site-packages")
else:
site_packages_pattern = os.path.join(venv_root, "lib", "python*", "site-packages")
site_packages_dirs = glob.glob(site_packages_pattern)
installed_pkgs = [p.split("==")[0] for p in get_installed_packages(site_packages_dirs) if p.startswith("azure-")]

# Get valid list of Azure SDK packages in repo
pkgs = discover_targeted_packages("", REPO_ROOT)
valid_azure_packages = [os.path.basename(p) for p in pkgs if "mgmt" not in p and "-nspkg" not in p]

# Filter current package and any excluded package
pkg_names = [
p for p in installed_pkgs if p in valid_azure_packages and p != pkg_name_to_exclude and p not in EXCLUDED_PKGS
]

logger.info("Installed azure sdk packages: %s", pkg_names)
return pkg_names


def uninstall_packages(executable: str, packages: List[str], working_directory: str):
"""
Uninstalls a list of packages from the virtual environment so dev build versions can be reinstalled.

:param executable: Path to the Python executable in the virtual environment.
:param packages: List of package names to uninstall.
:param working_directory: Directory from which to run the uninstall command.
:raises Exception: If uninstallation fails.
:return: None
"""
if len(packages) == 0:
logger.warning("No packages to uninstall.")
return

logger.info("Uninstalling packages: %s", packages)

try:
uninstall_from_venv(executable, packages, working_directory)
except Exception as e:
logger.error(f"Failed to uninstall packages: {e}")
raise e
logger.info("Uninstalled packages")


def install_packages(executable: str, packages: List[str], working_directory: str):
"""
Installs a list of packages from the devops feed into the virtual environment.

:param executable: Path to the Python executable in the virtual environment.
:param packages: List of package names to install.
:param working_directory: Directory from which to run the install command.
:raises Exception: If installation fails.
:return: None
"""

if len(packages) == 0:
logger.warning("No packages to install.")
return

logger.info("Installing dev build version for packages: %s", packages)

commands = [*packages, "--index-url", DEV_INDEX_URL]

# install dev build of azure packages
try:
install_into_venv(executable, commands, working_directory)
except Exception as e:
logger.error(f"Failed to install packages: {e}")
raise e
logger.info("Installed dev build version for packages")


def install_dev_build_packages(executable: str, pkg_name_to_exclude: str, working_directory: str):
# Uninstall GA version and reinstall dev build version of dependent packages
azure_pkgs = get_installed_azure_packages(executable, pkg_name_to_exclude)
uninstall_packages(executable, azure_pkgs, working_directory)
install_packages(executable, azure_pkgs, working_directory)


class devtest(Check):
def __init__(self) -> None:
super().__init__()

def register(
self, subparsers: "argparse._SubParsersAction", parent_parsers: Optional[List[argparse.ArgumentParser]] = None
) -> None:
"""Register the devtest check. The devtest check tests a package against dependencies installed from a dev index."""
parents = parent_parsers or []
p = subparsers.add_parser(
"devtest",
parents=parents,
help="Run the devtest check to test a package against dependencies installed from a dev index",
)
p.set_defaults(func=self.run)
p.add_argument(
"--pytest-args",
nargs=argparse.REMAINDER,
help="Additional arguments forwarded to pytest.",
)

def run(self, args: argparse.Namespace) -> int:
"""Run the devtest check command."""
logger.info("Running devtest check...")

set_envvar_defaults({"PROXY_URL": "http://localhost:5002"})
targeted = self.get_targeted_directories(args)

results: List[int] = []

for parsed in targeted:
package_dir = parsed.folder
package_name = parsed.name
executable, staging_directory = self.get_executable(args.isolate, args.command, sys.executable, package_dir)
logger.info(f"Processing {package_name} for devtest check")

# install dependencies
self.install_dev_reqs(executable, args, package_dir)

create_package_and_install(
distribution_directory=staging_directory,
target_setup=package_dir,
skip_install=False,
cache_dir=None,
work_dir=staging_directory,
force_create=False,
package_type="sdist",
pre_download_disabled=False,
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The install_dev_reqs call should be wrapped in a try-except block to handle potential failures gracefully, similar to how it's done in whl.py (lines 68-73). If dependency installation fails for one package, the check should log the error, add a failure code to results, continue to the next package, and not abort the entire run.

Example:

try:
    self.install_dev_reqs(executable, args, package_dir)
except Exception as exc:
    logger.error(f"Failed to install dev requirements for {package_name}: {exc}")
    results.append(1)
    continue

Copilot uses AI. Check for mistakes.
python_executable=executable,
)

if os.path.exists(TEST_TOOLS_REQUIREMENTS):
try:
install_into_venv(executable, ["-r", TEST_TOOLS_REQUIREMENTS], package_dir)
except Exception as e:
logger.error(f"Failed to install test tools requirements: {e}")
results.append(1)
continue
else:
logger.warning(f"Test tools requirements file not found at {TEST_TOOLS_REQUIREMENTS}.")
Comment on lines +173 to +183
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The create_package_and_install call should be wrapped in a try-except block to handle potential failures gracefully, similar to how it's done in whl.py (lines 75-90) and breaking.py. If package creation fails for one package, the check should log the error, add a failure code to results, continue to the next package, and not abort the entire run.

Example:

try:
    create_package_and_install(...)
except Exception as exc:
    logger.error(f"Failed to build/install package for {package_name}: {exc}")
    results.append(1)
    continue

Copilot uses AI. Check for mistakes.

try:
install_dev_build_packages(executable, package_name, package_dir)
except Exception as e:
logger.error(f"Failed to install dev build packages: {e}")
results.append(1)
continue

pytest_args = self._build_pytest_args(package_dir, args)

pytest_result = self.run_venv_command(
executable, ["-m", "pytest", *pytest_args], cwd=package_dir, immediately_dump=True
)

if pytest_result.returncode != 0:
if pytest_result.returncode == 5 and is_error_code_5_allowed(package_dir, package_name):
logger.info(
"pytest exited with code 5 for %s, which is allowed for management or opt-out packages.",
package_name,
)
# Align with tox: skip coverage when tests are skipped entirely
continue

logger.error(f"pytest failed for {package_name} with exit code {pytest_result.returncode}.")
results.append(pytest_result.returncode)

return max(results) if results else 0
2 changes: 2 additions & 0 deletions eng/tools/azure-sdk-tools/azpysdk/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from .verify_keywords import verify_keywords
from .generate import generate
from .breaking import breaking
from .devtest import devtest

from ci_tools.logging import configure_logging, logger

Expand Down Expand Up @@ -95,6 +96,7 @@ def build_parser() -> argparse.ArgumentParser:
verify_keywords().register(subparsers, [common])
generate().register(subparsers, [common])
breaking().register(subparsers, [common])
devtest().register(subparsers, [common])

return parser

Expand Down
23 changes: 0 additions & 23 deletions eng/tools/azure-sdk-tools/azpysdk/whl.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,26 +132,3 @@ def _install_common_requirements(self, executable: str, package_dir: str) -> Non
install_into_venv(executable, ["-r", TEST_TOOLS_REQUIREMENTS], package_dir)
else:
logger.warning(f"Test tools requirements file not found at {TEST_TOOLS_REQUIREMENTS}.")

def _build_pytest_args(self, package_dir: str, args: argparse.Namespace) -> List[str]:
log_level = os.getenv("PYTEST_LOG_LEVEL", "51")
junit_path = os.path.join(package_dir, f"test-junit-{args.command}.xml")

default_args = [
"-rsfE",
f"--junitxml={junit_path}",
"--verbose",
"--cov-branch",
"--durations=10",
"--ignore=azure",
"--ignore=.tox",
"--ignore-glob=.venv*",
"--ignore=build",
"--ignore=.eggs",
"--ignore=samples",
f"--log-cli-level={log_level}",
]

additional = args.pytest_args if args.pytest_args else []

return [*default_args, *additional, package_dir]
20 changes: 20 additions & 0 deletions eng/tools/azure-sdk-tools/ci_tools/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,10 +565,30 @@ def install_into_venv(venv_path_or_executable: str, requirements: List[str], wor

if pip_cmd[0] == "uv":
cmd += ["--python", py]

# todo: clean this up so that we're using run_logged from #42862
subprocess.check_call(cmd, cwd=working_directory)


def uninstall_from_venv(venv_path_or_executable: str, requirements: List[str], working_directory: str) -> None:
"""
Uninstalls the requirements from an existing venv (venv_path) without activating it.
"""
py = get_venv_python(venv_path_or_executable)
pip_cmd = get_pip_command(py)

install_targets = [r.strip() for r in requirements]
cmd = pip_cmd + ["uninstall"]
if pip_cmd[0] != "uv":
cmd += ["-y"]
cmd.extend(install_targets)

if pip_cmd[0] == "uv":
cmd += ["--python", py]

subprocess.check_call(cmd, cwd=working_directory)
Comment on lines +573 to +589
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's an inconsistency with the existing pip_uninstall function (line 518 in functions.py), which has a comment stating "we do not use get_pip_command here because uv pip doesn't have an uninstall command". However, this new uninstall_from_venv function does use get_pip_command and attempts to support uv.

According to recent uv documentation, uv pip uninstall is now supported. If this is intentionally adding support for uv uninstall, consider updating the pip_uninstall function and its comment for consistency. If uv uninstall is not yet stable or available in the version used by this project, this function may fail when TOX_PIP_IMPL=uv.

Copilot uses AI. Check for mistakes.
Copy link
Member Author

@JennyPng JennyPng Dec 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh i didn't know there was already a pip_uninstall function, will combine these

or ill just remove that comment?



def pip_install_requirements_file(requirements_file: str, python_executable: Optional[str] = None) -> bool:
return pip_install(["-r", requirements_file], True, python_executable)

Expand Down
Loading