diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 76bd801..8326599 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -3,17 +3,16 @@ name: Pytest Unit Tests on: [push] jobs: - build_and_test: + test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 name: Checkout code - - name: Test makefile - run: make init .env - - name: Check .env file - run: cat .env - - name: Create paths - run: make paths - - name: Initialize, Build, and Test with Docker - run: make test - shell: bash + - uses: actions/setup-python@v5 + name: Setup Python + with: + python-version: '3.12' + - name: Install dependencies + run: pip install -e . pytest httpx + - name: Run tests + run: pytest diff --git a/.gitignore b/.gitignore index 68bc17f..ca14c23 100644 --- a/.gitignore +++ b/.gitignore @@ -158,3 +158,6 @@ cython_debug/ # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ + +.pdm-python +.vscode/ diff --git a/.justfile b/.justfile new file mode 100644 index 0000000..861b887 --- /dev/null +++ b/.justfile @@ -0,0 +1,33 @@ +# List available commands +default: + @just --list --justfile {{justfile()}} + +# initialize the project +init: + @which pdm || echo "pdm not found, you'll need to install it: https://github.com/pdm-project/pdm" + @pdm install -G:all + @test -e .env || cp example.env .env + @which pre-commit && pre-commit install && pre-commit autoupdate || true + +# Build the project +build: init dcb + +# Run the pre-commit checks +checks: + @pre-commit run --all-files || { echo "Checking fixes\n" ; pre-commit run --all-files; } +check: checks + +# Run automated tests +test: + @pytest +tests: test +pytest: test + +# Build docker image +dcb: + @docker compose build + +# Start the node in docker +up: + @test -e .env || cp example.env .env + @docker compose up diff --git a/Dockerfile b/Dockerfile index 1c7fdc3..f01ddd4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ -FROM ghcr.io/ad-sdl/wei +FROM ghcr.io/ad-sdl/madsci:v0.8.0 LABEL org.opencontainers.image.source=https://github.com/AD-SDL/kla_module -LABEL org.opencontainers.image.description="Drivers and REST API's for the KLA devices" +LABEL org.opencontainers.image.description="Drivers and MADSci REST node for KLA devices" LABEL org.opencontainers.image.licenses=MIT ######################################### @@ -13,12 +13,9 @@ RUN mkdir -p kla_module COPY ./src kla_module/src COPY ./README.md kla_module/README.md COPY ./pyproject.toml kla_module/pyproject.toml -COPY ./tests kla_module/tests - -# RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y RUN --mount=type=cache,target=/root/.cache \ - pip install -e ./kla_module + uv pip install --python ${MADSCI_VENV}/bin/python -e ./kla_module CMD ["python", "kla_module/src/kla_rest_node.py"] diff --git a/Makefile b/Makefile deleted file mode 100644 index 5ff2934..0000000 --- a/Makefile +++ /dev/null @@ -1,30 +0,0 @@ - -.DEFAULT_GOAL := init - -.PHONY += init paths checks test clean - -init: # Do the initial configuration of the project - @test -e .env || cp example.env .env -ifeq ($(shell uname),Darwin) - @sed -i '' 's|^PROJECT_PATH=.*|PROJECT_PATH=$(shell pwd | sed 's/\//\\\//g')|' .env -else - @sed -i 's/^PROJECT_PATH=.*/PROJECT_PATH=$(shell pwd | sed 's/\//\\\//g')/' .env -endif - -.env: init - -paths: .env # Create the necessary data directories - @mkdir -p $(shell grep -E '^WEI_DATA_DIR=' .env | cut -d '=' -f 2) - @mkdir -p $(shell grep -E '^REDIS_DIR=' .env | cut -d '=' -f 2) - -checks: # Runs all the pre-commit checks - @pre-commit install - @pre-commit run --all-files || { echo "Checking fixes\n" ; pre-commit run --all-files; } - -test: init .env paths # Runs all the tests - @docker compose -f wei.compose.yaml --env-file .env up --build -d - @docker compose -f wei.compose.yaml --env-file .env exec kla_module pytest -p no:cacheprovider kla_module - @docker compose -f wei.compose.yaml --env-file .env down - -clean: - @rm .env diff --git a/README.md b/README.md index c00a5ad..f55e256 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,48 @@ # kla_module -A repository for KLA REST Node + +A [MADSci](https://github.com/AD-SDL/MADSci) node module for controlling a KLA Nanomechanics instrument through its HTTP control server. + +## Actions + +| Action | Arguments | Description | +| --------------- | --------------------------------------------- | --------------------------------------------------------------- | +| `load_protocol` | `protocol_files: list[str]`, `message: str?` | Load protocol files and move the stage to the sample load position | +| `run_protocol` | `protocol_files: list[str]`, `message: str?` | Run a batch of protocol (`.NMPROJ`) files | +| `check_status` | none | Query whether a sample run is in progress | + +`protocol_files` are paths on the KLA control PC, e.g. `C:\Users\Public\Documents\Nanomechanics\Profiles\Default\Make Indents.NMPROJ`. + +## Configuration + +Settings come from CLI flags, environment variables (prefixed `NODE_`), or a `.env` file: + +| Setting | Env var | Default | +| ----------------- | ---------------------- | ----------------------- | +| `kla_url` | `NODE_KLA_URL` | `http://127.0.0.1:8080` | +| `request_timeout` | `NODE_REQUEST_TIMEOUT` | `30.0` | +| `node_name` | `NODE_NAME` | `kla_node` | +| `node_url` | `NODE_URL` | `http://127.0.0.1:2000` | + +## Running + +With Docker: + +```bash +cp example.env .env # then edit KLA_URL / NODE_URL +docker compose up --build +``` + +Locally: + +```bash +pdm install -G:all +python src/kla_rest_node.py --kla_url http://:8080 --node_url http://0.0.0.0:3015 +``` + +## Development + +```bash +just init # install deps and pre-commit hooks +just test # run unit tests (no hardware needed) +just checks # run pre-commit +``` diff --git a/compose.yaml b/compose.yaml index 02a9368..62da28c 100644 --- a/compose.yaml +++ b/compose.yaml @@ -2,17 +2,16 @@ name: kla_module services: kla_module: container_name: kla_module - image: ${IMAGE} + image: ghcr.io/ad-sdl/kla_module + network_mode: host build: context: . dockerfile: Dockerfile tags: - - ${IMAGE}:latest - - ${IMAGE}:dev - command: python -m kla_rest_node --port 3015 --kla_url ${KLA_URL} + - ghcr.io/ad-sdl/kla_module:latest + - ghcr.io/ad-sdl/kla_module:dev env_file: .env - volumes: - - ./src:/home/app/kla_module/src - - ./tests:/home/app/kla_module/tests - ports: - - 3015:3015 \ No newline at end of file + environment: + - USER_ID=${USER_ID:-1000} + - GROUP_ID=${GROUP_ID:-1000} + command: python -m kla_rest_node --kla_url ${KLA_URL:-http://127.0.0.1:8080} diff --git a/example.env b/example.env index 9c2cfed..43fc4f2 100644 --- a/example.env +++ b/example.env @@ -1,8 +1,7 @@ -# Note: all paths are relative to the docker compose file -KLA_URL="http://127.0.0.1:8080" -PROJECT_PATH= -WEI_DATA_DIR=~/.wei -WORKCELL_FILENAME=test_workcell.yaml -WORKCELLS_DIR=${PROJECT_PATH}/tests/workcell_defs -IMAGE=ghcr.io/ad-sdl/kla_module -REDIS_DIR=~/.wei/redis +# Copy to .env and adjust for your setup +# URL of the KLA control server running on the instrument PC +KLA_URL=http://127.0.0.1:8080 +# MADSci node identity and the URL this node serves on +NODE_NAME=kla +NODE_MODULE_NAME=kla_module +NODE_URL=http://127.0.0.1:3015 diff --git a/pyproject.toml b/pyproject.toml index ae78b71..7c7cd35 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "kla_module" -version = "0.2.0" -description = "Software for automatting a KLA robot" +version = "1.0.0" +description = "Software for automating a KLA robot" authors = [ {name = "Ryan D. Lewis", email="ryan.lewis@anl.gov"}, {name = "Rafael Vescovi", email="ravescovi@anl.gov"}, @@ -11,15 +11,13 @@ authors = [ {name = "Tobias Ginsburg", email = "tginsburg@anl.gov"}, ] dependencies = [ - "ad_sdl.wei>=0.5.3", - "fastapi>=0.103.2", - "uvicorn>=0.21.1", - "pytest", + "madsci.node_module~=0.8.0", + "madsci.client~=0.8.0", + "madsci.common~=0.8.0", "requests", - ] -requires-python = ">=3.8.1" +requires-python = ">=3.10" readme = "README.md" license = {text = "MIT"} @@ -33,6 +31,14 @@ homepage = "https://github.com/AD-SDL/kla_module" requires = ["setuptools>=61", "wheel"] build-backend = "setuptools.build_meta" +[dependency-groups] +dev = [ + "pre-commit>=4.2.0", + "ruff>=0.11.7", + "pytest", + "httpx", +] + ##################### # Development Tools # ##################### @@ -70,8 +76,8 @@ exclude = [ line-length = 88 indent-width = 4 -# Assume Python 3.8 -target-version = "py38" +# Assume Python 3.10 +target-version = "py310" [tool.ruff.lint] # Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default. @@ -123,10 +129,11 @@ line-ending = "auto" [tool.pytest.ini_options] # https://docs.pytest.org/en/stable/customize.html addopts = "-x" +testpaths = ["tests"] +pythonpath = ["src"] junit_family="xunit1" filterwarnings = [ "ignore::DeprecationWarning", - "ignore::pottery.exceptions.InefficientAccessWarning", ] markers = [ "hardware: marks test as requiring hardware (deselect with '-m \"not hardware\"')", diff --git a/src/kla_driver/__init__.py b/src/kla_driver/__init__.py index e69de29..2207963 100644 --- a/src/kla_driver/__init__.py +++ b/src/kla_driver/__init__.py @@ -0,0 +1 @@ +"""Driver for the KLA Nanomechanics control server.""" diff --git a/src/kla_driver/kla_driver.py b/src/kla_driver/kla_driver.py index 359c71e..5b8ce8c 100644 --- a/src/kla_driver/kla_driver.py +++ b/src/kla_driver/kla_driver.py @@ -1,114 +1,90 @@ -import os -import time +"""Python driver for the KLA Nanomechanics HTTP control server.""" -import csv +from enum import IntEnum +from typing import Any, Optional import requests -class KLADriver(): - def __init__(self, url:str = "http://127.0.0.1:8080") -> None: - """Constructor for KLA driver class""" - - self.server_url = url - def send_request(self, request_data:dict = None): - """Attemps to send a HTTPS request with the request data - Parameters - ---------- - request_data : dict - A dictionary that contains request data +class KLARequestType(IntEnum): + """Request types understood by the KLA control server.""" - Returns - ------- - HTTPS response text - """ - try: - response = requests.post(self.server_url, json=request_data, headers={"Connection": "close"}) - return response.text - - except requests.ConnectionError as connection_err: - print(connection_err) - except requests.ConnectTimeout as timeout: - print(timeout) - except requests.HTTPError as http_err: - print(http_err) - except requests.JSONDecodeError as json_err: - print(json_err) - except ValueError as err: - print(err) - # else: - - def run_protocol(self, message:str = None, request_type:int = 1, status:int = 0, protocol_file_list:list = None): - """Creates the request data - Parameters - ---------- - message: str - A comment message (optional) - status int: - Status indicator - protocol_file_list:list - A list of protocol file paths - - Returns - ------- - HTTPS response text - """ - if not protocol_file_list: - raise ValueError("Protocol file list was not provided!") + RUN_BATCH = 1 + GET_SAMPLE_RUNNING_STATE = 2 + GO_TO_LOAD_SAMPLE = 4 + ECHO = 8 + GET_AT_LOAD_SAMPLE = 12 - data = { + +class KLADriver: + """Sends JSON requests to the KLA control server.""" + + def __init__( + self, url: str = "http://127.0.0.1:8080", timeout: float = 30.0 + ) -> None: + """Constructor for KLA driver class.""" + self.server_url = url + self.timeout = timeout + + def send_request( + self, + request_type: KLARequestType, + args: Optional[list[str]] = None, + message: Optional[str] = None, + status: int = 0, + ) -> str: + """Send a request to the KLA server and return the response text. + + Raises a requests exception if the server can't be reached or returns + an HTTP error status. + """ + data: dict[str, Any] = { "Message": message, - "RequestType": request_type, + "RequestType": int(request_type), "Status": status, - "Args": protocol_file_list + "Args": args or [], } - return self.send_request(request_data=data) - - def check_status(self): - pass - - def load_protocol(self, message:str = None, status:int = 0, protocol_file_list:list = None): - """Creates the request data - Parameters - ---------- - message: str - A comment message (optional) - status int: - Status indicator - protocol_file_list:list - A list of protocol file paths - - Returns - ------- - HTTPS response text - """ + response = requests.post( + self.server_url, + json=data, + headers={"Connection": "close"}, + timeout=self.timeout, + ) + response.raise_for_status() + return response.text + + def run_protocol( + self, protocol_file_list: list[str], message: Optional[str] = None + ) -> str: + """Run a batch of protocol (.NMPROJ) files.""" if not protocol_file_list: raise ValueError("Protocol file list was not provided!") + return self.send_request( + KLARequestType.RUN_BATCH, args=protocol_file_list, message=message + ) + + def load_protocol( + self, protocol_file_list: list[str], message: Optional[str] = None + ) -> str: + """Load protocol files and move the stage to the sample load position.""" + if not protocol_file_list: + raise ValueError("Protocol file list was not provided!") + return self.send_request( + KLARequestType.GO_TO_LOAD_SAMPLE, args=protocol_file_list, message=message + ) - data = { - "Message": message, - "RequestType": 4, - "Status": status, - "Args": protocol_file_list - } - return self.send_request(request_data=data) - - def get_output_file(self): - pass - - -# Usage example: -if __name__ == "__main__": - kla_url = "http://127.0.0.1:8080" - kla = KLADriver(hostname=kla_url) + def check_status(self) -> str: + """Query whether a sample run is in progress.""" + return self.send_request(KLARequestType.GET_SAMPLE_RUNNING_STATE) - RunBatch = 1 - GetSampleRunningState = 2 - GoToLoadSample = 4 - Echo = 8 - GetAtLoadSample = 12 - protocols = ["C:\\Users\\Public\\Documents\\Nanomechanics\\Profiles\\Default\\Make Indents.NMPROJ"] + def echo(self, message: str = "ping") -> str: + """Send an echo request, useful for checking connectivity.""" + return self.send_request(KLARequestType.ECHO, message=message) - response_text = kla.run_protocol(message="Test",request_type=RunBatch,protocol_file_list=protocols) - print(response_text) +if __name__ == "__main__": + kla = KLADriver(url="http://127.0.0.1:8080") + protocols = [ + "C:\\Users\\Public\\Documents\\Nanomechanics\\Profiles\\Default\\Make Indents.NMPROJ" + ] + print(kla.run_protocol(protocols, message="Test")) # noqa: T201 diff --git a/src/kla_rest_node.py b/src/kla_rest_node.py index 0eca99b..cd568a7 100644 --- a/src/kla_rest_node.py +++ b/src/kla_rest_node.py @@ -1,176 +1,88 @@ -import json -from argparse import ArgumentParser, Namespace -from contextlib import asynccontextmanager +"""MADSci REST node for the KLA Nanomechanics instrument.""" -from fastapi import FastAPI -from fastapi.responses import JSONResponse +from typing import Annotated, Optional -from wei.core.data_classes import ModuleStatus, StepResponse, StepFileResponse, StepStatus -import traceback +from madsci.common.types.node_types import RestNodeConfig +from madsci.node_module.helpers import action +from madsci.node_module.rest_node_module import RestNode +from pydantic import Field from kla_driver.kla_driver import KLADriver -def parse_args() -> Namespace: - """Parses the command line arguments for the KLA REST node""" - - parser = ArgumentParser() - parser.add_argument("--host", type=str, default="0.0.0.0", help="Host IP") - parser.add_argument("--port", type=str, default="3015", help="Port") - parser.add_argument("--kla_url", type=str, default="http://127.0.0.1:8080", help="URL for KLA") - - return parser.parse_args() - -global state, module_resources - -@asynccontextmanager -async def lifespan(app: FastAPI): - global kla, state, module_resources - """Initial run function for the KLA app, initializes the state - Parameters - ---------- - app : FastApi - The REST API app being initialized - - Returns - ------- - None""" - try: - # Do any instrument configuration here - args = parse_args() - kla = KLADriver(url=args.kla_url) - state = ModuleStatus.IDLE - module_resources = [] - except Exception as err: - print(err) - state = ModuleStatus.ERROR - - # Yield control to the application - yield - - # Do any cleanup here - pass - - -app = FastAPI( - lifespan=lifespan, -) - - -@app.get("/state") -def get_state(): - """Returns the current state of the module""" - global state - return JSONResponse(content={"State": state}) - - -@app.get("/about") -async def about(): - """Returns a description of the actions and resources the module supports""" - global state - return JSONResponse( - content={ - "name": "kla", - "model": "Unknown", - "version": "0.0.1", - "actions": { - "open_gate": "config : %s", - "close_gate": "config : %s", - "run_kla": "config : %s", - }, - "repo": "https://github.com/AD-SDL/kla_module.git" - }) - -@app.get("/resources") -async def resources(): - """Returns the current resources available to the module""" - global state, module_resources - resource_info = "" - if not (module_resources == ""): - with open(module_resources) as f: - resource_info = f.read() - return JSONResponse(content={"Resources": resource_info}) - - -@app.post("/action") -def do_action( - action_handle: str, # The action to be performed - action_vars: str, # Any arguments necessary to run that action -) -> StepResponse: - global kla, state - if state == ModuleStatus.BUSY: - return StepResponse( - action_response=StepStatus.FAILED, - action_msg="", - action_log="KLA is busy", - ) - state = ModuleStatus.BUSY - action_args = json.loads(action_vars) - - try: - if action_handle == "load_protocol": - - result = kla.load_protocol() - - state = ModuleStatus.IDLE - return StepResponse( - action_response=StepStatus.SUCCEEDED, - action_msg=result["action_msg"], - action_log=result["action_log"], - ) - - elif action_handle == "run_protocol": - - result = kla.run_protocol() - - state = ModuleStatus.IDLE - return StepResponse( - action_response=StepStatus.SUCCEEDED, - action_msg=result["action_msg"], - action_log=result["action_log"], - ) - - elif action_handle == "get_output_file": - - result = kla.get_output_file() - - file_name = result["action_msg"] - - state = ModuleStatus.IDLE - return StepFileResponse( - action_response=StepStatus.SUCCEEDED, - path=file_name, - action_log=result["action_log"], - ) - - else: - # Handle Unsupported actions - state = ModuleStatus.IDLE - return StepResponse( - action_response=StepStatus.FAILED, - action_msg="", - action_log="Unsupported action", - ) - except Exception as e: - print(str(e)) - print(traceback.format_exc()) - state = ModuleStatus.IDLE - return StepResponse( - action_response=StepStatus.FAILED, - action_msg="", - action_log=str(e), - ) +class KLANodeConfig(RestNodeConfig): + """Configuration for the KLA node module.""" + kla_url: str = Field( + default="http://127.0.0.1:8080", + description="URL of the KLA control server", + ) + request_timeout: float = Field( + default=30.0, + gt=0, + description="Timeout in seconds for requests to the KLA control server", + ) + + +ProtocolFiles = Annotated[ + list[str], + "Paths to protocol (.NMPROJ) files, as seen from the KLA control PC", +] +Message = Annotated[Optional[str], "Optional comment sent along with the request"] -if __name__ == "__main__": - import uvicorn - # Add any additional arguments here - args = parse_args() +class KLANode(RestNode): + """A node to control the KLA Nanomechanics instrument.""" - uvicorn.run( - "kla_rest_node:app", - host=args.host, - port=int(args.port), - reload=True, - ) \ No newline at end of file + kla: Optional[KLADriver] = None + config: KLANodeConfig = KLANodeConfig() + config_model = KLANodeConfig + module_version = "1.0.0" + + def startup_handler(self) -> None: + """Create the driver for the KLA control server.""" + self.kla = KLADriver( + url=self.config.kla_url, timeout=self.config.request_timeout + ) + self.logger.log_info(f"KLA node connected to {self.config.kla_url}") + + def shutdown_handler(self) -> None: + """Release the driver.""" + self.kla = None + + def state_handler(self) -> None: + """Report the node's current state.""" + self.node_state = { + "kla_url": self.config.kla_url, + "kla_interface_initialized": self.kla is not None, + } + + @action( + name="load_protocol", + description="Load protocol files and move the stage to the sample load position", + ) + def load_protocol( + self, protocol_files: ProtocolFiles, message: Message = None + ) -> str: + """Load protocol files and move the stage to the sample load position.""" + return self.kla.load_protocol(protocol_files, message=message) + + @action(name="run_protocol", description="Run a batch of protocol files") + def run_protocol( + self, protocol_files: ProtocolFiles, message: Message = None + ) -> str: + """Run a batch of protocol files.""" + return self.kla.run_protocol(protocol_files, message=message) + + @action( + name="check_status", + description="Query whether a sample run is in progress", + ) + def check_status(self) -> str: + """Query whether a sample run is in progress.""" + return self.kla.check_status() + + +if __name__ == "__main__": + kla_node = KLANode() + kla_node.start_node() diff --git a/src/test/run_test.py b/src/test/run_test.py deleted file mode 100755 index 0b89e10..0000000 --- a/src/test/run_test.py +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env python3 - -from pathlib import Path - -from wei import ExperimentClient - - -def main(): - # The path to the Workflow definition yaml file - wf_path = Path("./test_kla_workflow.yaml") - # This defines the Experiment object that will communicate with the server for workflows - exp = ExperimentClient("127.0.0.1", "8000", "Test_KLA_Application") - # This initializes the connection to the server and the logs for this run of the program. - exp.register_exp() - # This runs the workflow and returns once the workflow is complete - exp.start_run(wf_path.resolve(), simulate=False, blocking=True) - - -if __name__ == "__main__": - main() diff --git a/src/test/test_kla_workcell.yaml b/src/test/test_kla_workcell.yaml deleted file mode 100644 index 0ab3d5e..0000000 --- a/src/test/test_kla_workcell.yaml +++ /dev/null @@ -1,22 +0,0 @@ -name: Tecan_Test_Workcell - -#Info about data processing and location of the workcell -config: - funcx_local_ep: "" - globus_local_ep: "" - globus_search_index: "" - globus_portal_ep: "" - globus_group: "" - workcell_origin_coordinates: [0, 0, 0, 0, 0, 0] - -#List of all components accessible in this workcell -modules: - - name: KLA - model: kla_node - interface: wei_rest_node - config: - rest_node_address: "http://127.0.0.1:5558" - rest_node_auth: "" - workcell_coordinates: [0, 0, 0, 0, 0, 0] - -locations: {} diff --git a/src/test/test_kla_workflow.yaml b/src/test/test_kla_workflow.yaml deleted file mode 100644 index 07d9132..0000000 --- a/src/test/test_kla_workflow.yaml +++ /dev/null @@ -1,33 +0,0 @@ -name: Test Tecan -metadata: - author: Doga Ozgulbas, Ryan D. Lewis - info: Test workflow for Tecan - version: 0.1 - -modules: - - name: KLA - -flowdef: - - name: Load KLA protocol - module: KLA - action: load_protocol - args: - protocol_file_path: ../README.md - checks: null - comment: Load KLA protocol - - - name: Run KLA protocol - module: KLA - action: run_protocol - args: - {} - checks: null - comment: Run KLA protocol - - - name: Get Output KLA - module: KLA - action: get_output_file - args: - {} - checks: null - comment: Get KLA output file diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..94adb85 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,27 @@ +"""Shared fixtures for KLA module tests.""" + +from collections.abc import Generator +from unittest.mock import MagicMock, patch + +import pytest + + +@pytest.fixture(autouse=True) +def no_event_server() -> Generator[None, None, None]: + """Keep EventClients from trying to reach a real MADSci event manager.""" + mock_context = MagicMock() + mock_context.event_server_url = None + with patch( + "madsci.client.event_client.get_current_madsci_context", + return_value=mock_context, + ): + yield + + +@pytest.fixture +def mock_post() -> Generator[MagicMock, None, None]: + """Mock out HTTP requests to the KLA control server.""" + with patch("kla_driver.kla_driver.requests.post") as post: + post.return_value.text = "OK" + post.return_value.raise_for_status.return_value = None + yield post diff --git a/tests/test_base.py b/tests/test_base.py index 4a8d35f..8e4dd5a 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -1,25 +1,46 @@ -"""Base module tests.""" +"""Tests for the KLA driver.""" -import unittest +from unittest.mock import MagicMock +import pytest +import requests -class TestModule_Base(unittest.TestCase): - """Base test class for this module.""" +from kla_driver.kla_driver import KLADriver, KLARequestType - pass +PROTOCOLS = ["C:\\Profiles\\Default\\Make Indents.NMPROJ"] -class TestImports(TestModule_Base): - """Test the imports of the module are working correctly""" +def test_run_protocol_sends_run_batch(mock_post: MagicMock) -> None: + """run_protocol posts a RunBatch request with the protocol files.""" + driver = KLADriver(url="http://kla:8080", timeout=5) + assert driver.run_protocol(PROTOCOLS, message="hi") == "OK" + mock_post.assert_called_once() + args, kwargs = mock_post.call_args + assert args[0] == "http://kla:8080" + assert kwargs["timeout"] == 5 + assert kwargs["json"] == { + "Message": "hi", + "RequestType": int(KLARequestType.RUN_BATCH), + "Status": 0, + "Args": PROTOCOLS, + } - def test_driver_import(self): - """Test the driver and rest node imports""" - import kla_driver - import kla_rest_node - assert kla_driver - assert kla_rest_node +def test_load_protocol_sends_go_to_load_sample(mock_post: MagicMock) -> None: + """load_protocol posts a GoToLoadSample request.""" + KLADriver().load_protocol(PROTOCOLS) + assert mock_post.call_args.kwargs["json"]["RequestType"] == 4 -if __name__ == "__main__": - unittest.main() +def test_empty_protocol_list_rejected(mock_post: MagicMock) -> None: + """An empty protocol list raises before anything is sent.""" + with pytest.raises(ValueError, match="Protocol file list"): + KLADriver().run_protocol([]) + mock_post.assert_not_called() + + +def test_http_errors_propagate(mock_post: MagicMock) -> None: + """Connection and HTTP errors surface to the caller instead of being swallowed.""" + mock_post.side_effect = requests.ConnectionError("down") + with pytest.raises(requests.ConnectionError): + KLADriver().check_status() diff --git a/tests/test_module.py b/tests/test_module.py index 2754921..3b4e100 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -1,61 +1,69 @@ -"""Tests the basic functionality of the Module.""" +"""Tests for the KLA MADSci REST node.""" import time -import unittest -from pathlib import Path +from collections.abc import Generator +from typing import Any +from unittest.mock import MagicMock -import requests -from wei.core.data_classes import ModuleAbout, WorkcellData +import pytest +from fastapi.testclient import TestClient +from kla_rest_node import KLANode, KLANodeConfig -class TestWEI_Base(unittest.TestCase): - """Base class for WEI's pytest tests""" +PROTOCOLS = ["C:\\Profiles\\Default\\Make Indents.NMPROJ"] - def __init__(self, *args, **kwargs): - """Basic setup for WEI's pytest tests""" - super().__init__(*args, **kwargs) - self.root_dir = Path(__file__).resolve().parent.parent - self.workcell_file = self.root_dir / Path( - "tests/workcell_defs/test_workcell.yaml" + +@pytest.fixture +def client() -> Generator[TestClient, None, None]: + """A test client for a KLA node with no MADSci managers attached.""" + node = KLANode( + node_config=KLANodeConfig( + node_name="kla_test", + kla_url="http://kla:8080", + enable_registry_resolution=False, ) - self.workcell = WorkcellData.from_yaml(self.workcell_file) - self.server_host = self.workcell.config.server_host - self.server_port = self.workcell.config.server_port - self.url = f"http://{self.server_host}:{self.server_port}" - self.module_url = "http://kla_module:3015" - self.redis_host = self.workcell.config.redis_host - - # Check to see that server is up - start_time = time.time() - while True: - try: - if requests.get(self.url + "/wc/state").status_code == 200: - break - except Exception: - pass - time.sleep(1) - if time.time() - start_time > 60: - raise TimeoutError("Server did not start in 60 seconds") - while True: - try: - if requests.get(self.module_url + "/state").status_code == 200: - break - except Exception: - pass - time.sleep(1) - if time.time() - start_time > 60: - raise TimeoutError("Module did not start in 60 seconds") - - -class TestModuleInterfaces(TestWEI_Base): - """Tests the basic functionality of the Module.""" - - def test_module_about(self): - """Tests that the module's /about endpoint works""" - response = requests.get(self.module_url + "/about") - assert response.status_code == 200 - ModuleAbout(**response.json()) - - -if __name__ == "__main__": - unittest.main() + ) + node.start_node(testing=True) + with TestClient(node.rest_api) as test_client: + deadline = time.time() + 10 + while not test_client.get("/status").json().get("ready"): + assert time.time() < deadline, "Node never became ready" + time.sleep(0.1) + yield test_client + + +def run_action(client: TestClient, name: str, args: dict[str, Any]) -> dict: + """Create, start, and wait for an action, returning its final result.""" + response = client.post(f"/action/{name}", json={"args": args}) + assert response.status_code == 200, response.text + action_id = response.json()["action_id"] + response = client.post(f"/action/{name}/{action_id}/start") + assert response.status_code == 200, response.text + deadline = time.time() + 10 + while time.time() < deadline: + result = client.get(f"/action/{action_id}/result").json() + if result.get("status") in ("succeeded", "failed", "cancelled"): + return result + time.sleep(0.1) + raise AssertionError(f"Action {name} timed out") + + +def test_info_lists_actions(client: TestClient) -> None: + """The node advertises its actions and their arguments.""" + info = client.get("/info").json() + assert set(info["actions"]) == {"load_protocol", "run_protocol", "check_status"} + assert info["actions"]["run_protocol"]["args"]["protocol_files"]["required"] + + +def test_run_protocol(client: TestClient, mock_post: MagicMock) -> None: + """run_protocol forwards the files to the KLA server and succeeds.""" + result = run_action(client, "run_protocol", {"protocol_files": PROTOCOLS}) + assert result["status"] == "succeeded", result + assert mock_post.call_args.kwargs["json"]["Args"] == PROTOCOLS + + +def test_device_error_fails_action(client: TestClient, mock_post: MagicMock) -> None: + """A KLA server error marks the action as failed.""" + mock_post.return_value.raise_for_status.side_effect = RuntimeError("500") + result = run_action(client, "check_status", {}) + assert result["status"] == "failed", result diff --git a/tests/workcell_defs/test_workcell.yaml b/tests/workcell_defs/test_workcell.yaml deleted file mode 100644 index d9796dc..0000000 --- a/tests/workcell_defs/test_workcell.yaml +++ /dev/null @@ -1,19 +0,0 @@ -name: Test_Workcell - -#Info about data processing and location of the workcell -config: - workcell_origin_coordinates: [0, 0, 0, 0, 0, 0] - redis_host: "wei_redis" - server_host: "wei_server" - server_port: 8000 - -#List of all components accessible in this workcell -modules: - - - name: kla_module - model: KLA - interface: wei_rest_node - config: - rest_node_address: "http://kla_module:3015" - workcell_coordinates: [0, 0, 0, 0, 0, 0] -locations: {} diff --git a/tests/workflow_defs/test_workflow.yaml b/tests/workflow_defs/test_workflow.yaml deleted file mode 100644 index 40d54f8..0000000 --- a/tests/workflow_defs/test_workflow.yaml +++ /dev/null @@ -1,33 +0,0 @@ -name: Test KLA Module -metadata: - author: Doga Ozgulbas - info: Tests the functionality of the KLA Module - version: 0.1 - -modules: - - name: kla_module - -flowdef: - - name: Load KLA protocol - module: kla_module - action: load_protocol - args: - protocol_file_path: ../README.md - checks: null - comment: Load KLA protocol - - - name: Run KLA protocol - module: kla_module - action: run_protocol - args: - {} - checks: null - comment: Run KLA protocol - - - name: Get Output KLA - module: kla_module - action: get_output_file - args: - {} - checks: null - comment: Get KLA output file diff --git a/wei.compose.yaml b/wei.compose.yaml deleted file mode 100644 index c00725f..0000000 --- a/wei.compose.yaml +++ /dev/null @@ -1,48 +0,0 @@ -include: [compose.yaml] -##################### -# WEI Core Services # -##################### -services: - wei_server: - image: ghcr.io/ad-sdl/wei - container_name: wei_server - ports: - - 8000:8000 - env_file: .env - environment: - - PYTHONUNBUFFERED=1 # Fix weird bug with empty logging - volumes: - - ${WORKCELLS_DIR}:/workcell_defs - - ${WEI_DATA_DIR}:/home/app/.wei - - diaspora_config:/home/app/.diaspora - command: python3 -m wei.server --workcell /workcell_defs/${WORKCELL_FILENAME} - depends_on: - - wei_redis - wei_engine: - image: ghcr.io/ad-sdl/wei - container_name: wei_engine - volumes: - - ${WORKCELLS_DIR}:/workcell_defs - - ${WEI_DATA_DIR}:/home/app/.wei - env_file: .env - environment: - - PYTHONUNBUFFERED=1 # Fix weird bug with empty logging - command: python3 -m wei.engine --workcell /workcell_defs/${WORKCELL_FILENAME} - depends_on: - - wei_redis - - wei_server - wei_redis: - image: redis - container_name: wei_redis - ports: - - 6379:6379 - volumes: - - ${REDIS_DIR}:/data - command: redis-server --save 60 1 --loglevel warning - -################ -# Data Storage # -################ -volumes: - diaspora_config: - driver: local